Summing elements within an eval statement, in a for loop

I have written a complete code that runs in MATLAB, but outputs a slightly incorrect result. I need to get the following:
utotal
where
utotal = S1plot + S2plot + ...
until the digit equals (N/2) + 1, where N is even. If N = 10, say, the digit would be 6.
Then I need to evaluate utotal within the script. How can I achieve this?
This is what I have so far:
N = 10;
for alpha = 1:(N/2+1)
eval(['utotal = sum(S' num2str(alpha) 'plot);'])
end
but it doesn't work because it evaluates the following:
u1 = sum(S1plot);
u1 = sum(S2plot);
u1 = sum(S3plot);
u1 = sum(S4plot);
u1 = sum(S5plot);
u1 = sum(S6plot);
Thanks in advance for help.

 채택된 답변

Geoff Hayes
Geoff Hayes 2015년 10월 29일
Abhi - since you are summing elements on each iteration of a for loop, you would need to do something like
N = 10;
utotal = 0;
for alpha = 1:(N/2+1)
utotal = utotal + ...;
end
Use of eval is strongly discouraged as you have noticed with problems in your code. Why are you creating all of the different variables named SXPlot? Why not just create an array for all of these value?

댓글 수: 2

Edited: N is even. Geoff, I am really on the verge of completing my project, and I have used eval statements everywhere, so I am trying to use that here. I will keep the array concept in mind for next time.
If I were marking, I would deduct marks for using eval() unless the student could convince me there was no other way.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Language Support에 대해 자세히 알아보기

질문:

2015년 10월 29일

댓글:

2015년 10월 30일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by