在 for 循环中对 eval 语句中的元素求和

Summing elements within an eval statement, in a for loop

我已经编写了一个在 MATLAB 中运行的完整代码,但输出了一个稍微不正确的结果。我需要得到以下信息:

utotal

哪里

utotal = S1plot + S2plot + ... 

直到数字等于 (N/2) + 1,其中 N 为偶数。例如,如果 N = 10,则数字将为 6。

然后我需要在脚本中计算 utotal。我怎样才能做到这一点?

这是我目前所拥有的:

N = 10;
for alpha = 1:(N/2+1)
    eval(['utotal = sum(S' num2str(alpha) 'plot);'])
end

但它不起作用,因为它评估以下内容:

utotal = sum(S1plot);
utotal = sum(S2plot);
utotal = sum(S3plot);
utotal = sum(S4plot);
utotal = sum(S5plot);
utotal = sum(S6plot);

在此先感谢您的帮助。

N = 10;
Result =0;
for alpha = 1:(N/2+1)
   Result = Result + num2str(alpha)
end
eval(['utotal = sum(S' Result 'plot);'])

See the comments by @beaker. This solution does not do what the OP wants.

我还没有测试过,但应该可以。

N=10;
for alpha = 1:(N/2+1)
    allSum = [allSum 'sum(S' num2str(alpha) 'plot)+'];
end

allSum(end)=';';
eval(['utotal = ' allSum]);

这是您现在可以使用的解决方法。请注意,这是非常糟糕的编码习惯,您现在遇到的困难只是您不应该这样做的原因之一。

%// Generate random data
S1plot = randi(100,51,5);
S2plot = randi(100,51,5);
S3plot = randi(100,51,5);
S4plot = randi(100,51,5);
S5plot = randi(100,51,5);
S6plot = randi(100,51,5);
N = 10;

%// Put individual matrices into 3D matrix S
%// To access matrix Snplot, use S(:,:,n)
%// This is the format these variables should have been in in the first place
for alpha = 1:(N/2+1)
    eval(['S(:,:,' num2str(alpha) ') = (S' num2str(alpha) 'plot);'])
end

%// Now sum along the third dimension
utotal = sum(S,3);