how do i do a for loop to find different array sizes
1 次查看(过去 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!