Merge output as one matrix in for loop

조회 수: 1 (최근 30일)
ammar ansari
ammar ansari 2015년 5월 20일
댓글: Stephen23 2015년 5월 23일
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
ammar ansari
ammar ansari 2015년 5월 20일
I want to represent my output in a matrix form. Command A = [A;i j] provided me the desired output. Thanks for the help

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by