Merge output as one matrix in for loop
2 次查看(过去 30 天)
显示 更早的评论
I have created a program
function A = large_elements(X)
[rows,column]=size(X);
cnt=0;
for i=1:rows%rows indices
for j=1:column%column indices
cnt=i+j;
if cnt<X(i,j)
A=[i j]
else
A=[]
end
end
end
end
When I run the function I get my output
large_elements([1 4; 5 2; 6 0])
A =
1 2
A =
2 1
A =
3 1
ans =
3 1
I can't store my output. It overwrites my previous result How can I represent all values of A in matrix form?
回答(1 个)
Stephen23
2015-5-21
编辑:Stephen23
2015-5-21
The function given in the question locates every element of the input matrix X whose value is greater than the sum of its indices, and returns these indices, e.g.:
>> Z = large_elements(5*ones(3))
Z =
1 1
1 2
1 3
2 1
2 2
3 1
Solving this kind of problem using two nested loops is very poor use of MATLAB, especially as the output array is growing inside the loops: without any array preallocation this is a slow and very inefficient use of MATLAB. It would be much faster and much simpler using vectorized code, such as these three lines:
function Z = large_elements(X)
[r,c] = size(X);
Y = bsxfun(@plus, (1:r)', 1:c);
Z = X>Y;
and outputs this:
>> Z = large_elements(5*ones(3))
Z =
1 1 1
1 1 0
1 0 0
which are the logical indices of those values. Using logical indices is usually the fastest way of accessing and identifying elements of an array, so this would be an excellent choice of output. If it is strictly required to use subscript indices, then simply use find on the logical indices:
>> [r,c] = find(Z)
r =
1
2
3
1
2
1
c =
1
1
1
2
2
3
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!