1 view (last 30 days)

Hi Guys :)

I'd like to group calculated values of for loops together so I can create a boxplot of them.

Suggestions and help would be much appreciated, since I can't find a proper and easy way to do this.

Thank you in advance :)

Guillaume
on 14 Feb 2020

I'm not entirely clear on what you mean by boxplot nor what you're trying to achieve since none of the pieces of code you posted work. perhaps in the first one you meant to write

e = [0.1 0.2 0.8 0.9]

r = [0.9 1.2 2.8 7.9]

for i = length(e)

cs=e*2.93.*r; % .* instead of *

for d = 70:-1:0

b=cs.^2.*e+d; % .^ instead ^

end

end

which at least doesn't error even if it overwrites cs and b on each steps of the loop.

If you meant to create cs for each possible combination of e and r, and create b for each combinatio of e, r and d, then you don't need a loop:

%to create all combinations, the input vectors must each be in a different direction

e = [0.1; 0.2; 0.8; 0.9]; %column vector Mx1

r = [0.9, 1.2, 2.8, 7.9]; %row vector 1xN

d = permute(70:-1:0, [1, 3, 2]); %vector in 3rd dimension, 1x1xP

cs = 2.93 * e .* r; %2D matrix, MxN

b = cs.^2 .* e + d; %3D matrix, MxNxP

and to create the desired table:

[ee, rr, dd] = ndgrid(e, r, d);

table(ee(:), rr(:), cs(:), dd(:), b(:), 'VariableNames', {'e', 'r', 'cs', 'd', 'b'})

Note that If you were to use loops the code would go like this:

e = [0.1, 0.2, 0.8, 0.9]; % 1xM

r = [0.9, 1.2, 2.8, 7.9]; % 1xN

d = 70:-1:0; % 1xP

cs = zeros(numel(e), numel(r)); %preallocate MxN matrix

d = zeros(numel(e), numel(r), numel(d)); %preallocate MxNxP matrix

for eidx = 1:numel(e)

cs(eidx, :) = 2.93 * e(eidx) .* r;

for didx = 1:numel(d)

b(eidx, :, didx) = cs(eidx, :).^2 .* e(eidx) + d(didx);

end

end

Overall, much simpler without the loop.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Direct link to this comment

https://uk.mathworks.com/matlabcentral/answers/505516-grouping-calculated-values-of-for-loops-together#comment_797380

⋮## Direct link to this comment

https://uk.mathworks.com/matlabcentral/answers/505516-grouping-calculated-values-of-for-loops-together#comment_797380

## Direct link to this comment

https://uk.mathworks.com/matlabcentral/answers/505516-grouping-calculated-values-of-for-loops-together#comment_797393

⋮## Direct link to this comment

https://uk.mathworks.com/matlabcentral/answers/505516-grouping-calculated-values-of-for-loops-together#comment_797393

Sign in to comment.