How do I loop a command for different variable names?

조회 수: 55 (최근 30일)
Matthew Foster
Matthew Foster 2022년 3월 25일
편집: Torsten 2022년 3월 26일
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
David Hill
David Hill 2022년 3월 25일
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

댓글을 달려면 로그인하십시오.

답변 (2개)

Walter Roberson
Walter Roberson 2022년 3월 25일
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 2022년 3월 25일
편집: Torsten 2022년 3월 26일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by