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.

 Respuesta aceptada

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 comentarios

asldkfj
asldkfj el 29 de Oct. de 2015
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

el 29 de Oct. de 2015

Comentada:

el 30 de Oct. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by