how do i do a for loop to find different array sizes

1 view (last 30 days)
%say each matrix is
mode1 = [1 2 3];
mode2 = [4 5 6];
mode3 = [7 8 9 10];
mode4 = [11 12 13 14 15 16];
mode5 = [17 18 19 20 21];
%want to return the size of each one as k1 = 3, k2 = 3, k3 = 4, k4 = 6, k5 = 5
for i = 1:5
f(i) = size(mode(i))
end
How can I fix this?
Thanks

Accepted Answer

David Fletcher
David Fletcher on 13 Mar 2018
Edited: David Fletcher on 13 Mar 2018
mode would have to be a cell array since the number of columns of each array is not the same i.e
mode{1} = [1 2 3];
mode{2} = [4 5 6];
mode{3} = [7 8 9 10];
mode{4} = [11 12 13 14 15 16];
mode{5} = [17 18 19 20 21];
for i = 1:5
f(i) = length(mode{i}) %if they are always going to be vectors
end
For efficiency, you may also wish to consider pre-allocating the size of f
Instead of the length() function you could also use size() in the following ways:
for i = 1:5
f(i) = size(mode{i},2) %if the are always going to be row vectors
end
or
for i = 1:5
[frows(i),fcols(i)] = size(mode{i}) %obtain both row and column size
end
or
for i = 1:5
[~,fcols(i)] = size(mode{i}) %ignores the rows output from size function
end
The loop could be omitted completely with
cellfun(@length,mode)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!