Merge output as one matrix in for loop
이전 댓글 표시
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?
댓글 수: 3
James Tursa
2015년 5월 20일
편집: James Tursa
2015년 5월 21일
Are you looking for a way to fix up this function as you have it coded? (e.g., you could replace A = [i j] with A = [A;i j] and get rid of the else clause), or would you like us to suggest ways to vectorize this (eliminate the for loops)?
ammar ansari
2015년 5월 20일
Stephen23
2015년 5월 23일
답변 (1개)
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
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!