Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
Steven Martin
Steven Martin am 13 Mär. 2018
Bearbeitet: David Fletcher am 13 Mär. 2018
%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

Akzeptierte Antwort

David Fletcher
David Fletcher am 13 Mär. 2018
Bearbeitet: David Fletcher am 13 Mär. 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)

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by