필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

counting elements in multiple variables, in a for loop

조회 수: 1 (최근 30일)
Tom Edwards
Tom Edwards 2020년 11월 10일
마감: MATLAB Answer Bot 2021년 8월 20일
I have several 1 dimensional arrays of differing lengths, each contains a different number of values. I'd simply like to count the elements of each and store that number in another vector. I can't do it in a for loop as I understand them now e.g. in the code below Is there someway of doing it with strings? How do I use the index i in a variable name e.g M1, M2 etc...
divisors = zeros(20,1)
for i = 1:20
divisors(i) = M(i)
end
Is it possible to use a for loop to call different variables in general? I'd also like to get the row indices for each element in a collection of logical arrays, at the moment i'm doing it one by one but its long and ugly and I'm using find which is an 'expensive' function. Is there a better way?
  댓글 수: 2
David Hill
David Hill 2020년 11월 10일
편집: David Hill 2020년 11월 10일
Generally, you should never make arrays with different variable names (M1, M2, ....) but if they have different lengths just use a cell array.
M{1}=[1 2 3];
M{2}=[5 6 7 8 9];
M{3}=[1 9 2 9 7 3 2 3];
for k=1:length(M)
divisors(k)=length(M{k});
end
Stephen23
Stephen23 2020년 11월 10일
"How do I use the index i in a variable name e.g M1, M2 etc..."
Putting numbers into variable names like that is a sign that you are doing something wrong.
Putting meta-data (e.g. pseudo-indices) into variable names is a sign that you are doing something wrong.
The better** solution is to use actual indices into one array, just like the MATLAB documentation recommends.
** better in the sense simpler, neater, faster, more efficient, better use of memory, less buggy, easier to debug, etc.

답변 (1개)

Steven Lord
Steven Lord 2020년 11월 10일
Can you define variables with numbered names like M1, M2, M3, ... ? Yes.
Should you do this? Generally we recommend against it. For the situation you described I'd probably store the mixed-length vectors in a cell array.

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by