counting elements in multiple variables, in a for loop

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 Comments

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
"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.

Answers (1)

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.

This question is closed.

Tags

Asked:

on 10 Nov 2020

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!