この質問は閉じられています。 編集または回答するには再度開いてください。

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)
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 件のコメント
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