Summing elements within an eval statement, in a for loop
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Geoff Hayes
on 29 Oct 2015
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 Comments
Walter Roberson
on 30 Oct 2015
If I were marking, I would deduct marks for using eval() unless the student could convince me there was no other way.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!