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 日

1 投票

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 件のコメント

asldkfj
asldkfj 2015 年 10 月 29 日
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.
Walter Roberson
Walter Roberson 2015 年 10 月 30 日
If I were marking, I would deduct marks for using eval() unless the student could convince me there was no other way.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLanguage 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