Most efficient way of creating variables

3 views (last 30 days)
I have 8 matrices, (13x10) ,which contain velocites of a flow within a channel (V1,V2.....V8). For each of these I have extarcted the lasts columns using the following :
E1 = V1(:,10);
E2 = V2(:,10);
E3 = V3(:,10);
......
E8 = V8(:,10);
I read the following https://uk.mathworks.com/matlabcentral/answers/57445-faq-how-can-i-create-variables-a1-a2-a10-in-a-loop which mentions that dynamic variable names should be avoided where possible.
In accordance, I attempted to try what the post suggested (Making one matrix with the 8 columns (E):
E = zeros(13,8); % Each column to be replaced by the last columns of V1,V2..V8
for i = [1:8];
E(i) = V(i)(:,10); % Trying to assign final columns of V1,V2..V8 to the columns of E8
end
However, I feel as if this is very far from the correct way of doing this. Any help is appreciated

Accepted Answer

Adam Danz
Adam Danz on 12 Mar 2021
Edited: Adam Danz on 12 Mar 2021
It's good that you're following that advice.
E = [V1(:,10), V2(:,10), . . ., Vn(:,10)]; % most efficient method of this list
If you want to use a loop, the variables have be to combined before hand,
V = {V1, V2, V3, . . ., Vn};
E = zeros(size(V1,1), numel(v));
for i = 1:numel(V)
E(:,i) = V{i}(:,10);
end
or, if the Vn matrices are all the same size,
V = cat(3, V1, V2, V3, . . ., Vn);
E = squeeze(V(:,10,:));
  1 Comment
James Rodriguez
James Rodriguez on 13 Mar 2021
Thank you very much! This is very useful information and I really appreciate the alternate methods.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!