Merge output as one matrix in for loop
Afficher commentaires plus anciens
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
James Tursa
le 20 Mai 2015
Modifié(e) : James Tursa
le 21 Mai 2015
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
le 20 Mai 2015
Stephen23
le 23 Mai 2015
Réponses (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
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!