Merge output as one matrix in for loop

1 vue (au cours des 30 derniers jours)
ammar ansari
ammar ansari le 20 Mai 2015
Commenté : Stephen23 le 23 Mai 2015
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 commentaires
ammar ansari
ammar ansari le 20 Mai 2015
I want to represent my output in a matrix form. Command A = [A;i j] provided me the desired output. Thanks for the help

Connectez-vous pour commenter.

Réponses (1)

Stephen23
Stephen23 le 21 Mai 2015
Modifié(e) : Stephen23 le 21 Mai 2015
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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by