how do i do a for loop to find different array sizes
조회 수: 3 (최근 30일)
이전 댓글 표시
%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
댓글 수: 0
채택된 답변
David Fletcher
2018년 3월 13일
편집: David Fletcher
2018년 3월 13일
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)
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!