PDA

查看完整版本 : [MATLAB基础] 循环嵌套的疑问


argchina
2009-05-17, 22:43
我是初学者,有一个问题想请教大家。

在循环嵌套中的内循环的的for 语句中能不能包含父循环for 语句中的循环指数?
例子:
clear all;

x = input('entrer un chiffre entier impair : ');
if mod(x,2)==0
fprintf('%.0f n''est pas un chiffre entier impair \n',x);
else
str_space='';
for k=1:(x+1)/2
for n=1:1:(x-(2k-1)/2)/2
str_space=strcat(str_space,' ');
end
for n=1:(2k-1)
str_etoile=strcat(str_etoile,'*');
end
str_result=[str_space str_etoile str_space];
fprintf('%s \n',str_result);
end
end

系统说“for n=1:1:(x-(2k-1)/2)/2 ”有错误“Unexpected MATLAB expression.”。我不知道那里出错了,那一位朋友帮我找出为什么出错?谢谢!

argchina
2009-05-17, 22:49
上面的人脸是冒号“:”

TTT_IOU
2009-05-17, 23:15
程序中的2k应为2*k,且str_etoile='';
clear all;
x = input('entrer un chiffre entier impair : ');
if mod(x,2)==0
fprintf('%.0f n''est pas un chiffre entier impair \n',x);
else
str_space='';
str_etoile='';
for k=1: (x+1)/2
for n=1: (x-(2*k-1)/2)/2
str_space=strcat(str_space,' ');
end
for n=1: (2*k-1)
str_etoile=strcat(str_etoile,'*');
end
str_result=[str_space str_etoile str_space];
fprintf('%s \n',str_result);
end
end
不过程序中的str_space='';不起作用,因为矩阵对空格不显示;

argchina
2009-05-18, 10:32
谢谢!那么如何才能根据n来得到含有n个空格的字符串呢?

argchina
2009-05-18, 10:40
我知道了用blanks(n)来生成含有n个空格的字符串。但是在应用中
clear all;
% demande des donn/es a l'usager
x = input('entrer un chiffre entier impair : ');
if mod(x,2)==0
fprintf('%.0f n''est pas un chiffre entier impair \n',x);
else

for k=1:(x+1)/2
str_space = '';
str_etoile = '';
str_space=blanks((x-(2*k-1)/2)/2);
for n=1:(2*k-1)
str_etoile=strcat(str_etoile,'*');
end
str_result=[str_space str_etoile str_space];
fprintf('%s \n',str_result);
end
end

却告诉我:
Warning: Size vector should be a row vector with integer elements.
> In blanks at 13
In exe1 at 13
这是为什么呢?谢谢!

argchina
2009-05-18, 10:46
谢谢TTT IOU,我已经自己解决了问题!