Reputation: 137
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:
utotal = sum(S1plot);
utotal = sum(S2plot);
utotal = sum(S3plot);
utotal = sum(S4plot);
utotal = sum(S5plot);
utotal = sum(S6plot);
Thanks in advance for help.
Upvotes: 0
Views: 67
Reputation: 9075
See the comments by @beaker. This solution does not do what the OP wants.
I haven't tested this but it should work.
N=10;
for alpha = 1:(N/2+1)
allSum = [allSum 'sum(S' num2str(alpha) 'plot)+'];
end
allSum(end)=';';
eval(['utotal = ' allSum]);
Upvotes: 1
Reputation: 16821
Here's a workaround you can use for now. Note that this is extremely bad coding practice and the difficulty you're having now is only one of the reasons you shouldn't do it.
%// 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);
Upvotes: 2
Reputation: 697
N = 10;
Result =0;
for alpha = 1:(N/2+1)
Result = Result + num2str(alpha)
end
eval(['utotal = sum(S' Result 'plot);'])
Upvotes: 0