How do I loop a command for different variable names?

59 views (last 30 days)
I'm working on a project where I have four sets of data that need several operations done to each set and am trying to shorten up the code.
Say one operation is reshape, and then several other operations, so for starters:
alpha_list = reshape(alpha, x*y, 1);
beta_list = reshape(beta, x*y, 1);
gamma_list = reshape(gamma, x*y, 1);
nu_list = reshape(nu, x*y, 1);
... and then maybe three other things that each need to be done to each set.
I could rename alpha, beta, gamma, nu simply a, b, g, n if needed.
What I want to find out is how to create a "for" loop that uses an array storing part of the names (for alpha_list, alpha)
so if I had an array = [a b g n] it could perform the operation for a_list, b_list, g_list, n_list, if I could say:
for i = 1:4
array(i)_list = reshape(array(i), x*y, 1);
end
I guess the problem is that array(1)_list is not the same as a_list, and this may require some additional lines of code, maybe append in order to get the loop to work that way, but it could still save me many lines if I can get the loop to work.
Thanks in advance!
  1 Comment
David Hill
David Hill on 25 Mar 2022
You should always avoid multiple variables with similar names. Much better to index into a single variable (use 3D array).
alpha_list=randi(100,10,10,5);%store all your lists in a single variable
for k=1:5
A(:,k)=reshape(alpha_list(:,:,k),[],1);%then it is much easier to work with
end

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 25 Mar 2022
It is possible to do that, but we firmly recommend against doing that.
I suggest using a cell array for your case, which would also allow you to use more compact code.
C = {alpha, beta, gamma, nu};
array_list = cellfun(@(m) reshape(m, [], 1), 'uniform', 0);
array_list{1} is now alpha(:), array_list{2} is now beta(:) and so on.

Jeff Miller
Jeff Miller on 25 Mar 2022
Edited: Torsten on 26 Mar 2022
Another alternative is to make a function that does all of the necessary operations on each vector, and then call that function once for each vector, something like
function [reshaped, operation2result, operation3result] = manyoperations(inputvector)
reshaped = reshape(inputvector,[],1);
% other operations on this input vector as needed
end
[alpha_list, alpha2, alpha3] = manyoperations(alpha);
[beta_list, beta2, beta3] = manyoperations(beta);
% etc

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!