Info
此问题已关闭。 请重新打开它进行编辑或回答。
counting elements in multiple variables, in a for loop
1 次查看(过去 30 天)
显示 更早的评论
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
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
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
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.
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!