开发者

matlab: summing if/elseif displayed variables in a for loop

I'm wondering if it's possible t开发者_高级运维o get the sum of displayed strings in a for loop. for example, assuming:

a=5;
b=10;
c=15;
d=20;


if sum(x)==1    
  disp(num2str(a))    
  elseif sum(x)==2    
  disp(num2str(b))    
elseif sum(x)==3    
  disp(num2str(c))    
elseif sum(x)==4    
  disp(num2str(d))    
else disp('0')

If I get the results in a for loop:

loop 1 gets: a=5

loop 2 gets: b=10

loop 3 gets: d=20

loop 4 gets: b=10

Is there any way I can get the sum of results, in this case being a+b+d+b=45 ?


A friend has showed me the answer, here it is:

if sum(x)==1
    disp([num2str(a)])
    results=results+a;
elseif sum(x)==2
    disp([num2str(b)])
    results=results+b;
elseif sum(x)==3
    disp([num2str(c)])
    results=results+c;
elseif sum(x)==4
    disp([num2str(d)])
    results=results+d;
else disp('0')
end
disp(results)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜