How can I change the elements of a matrix in new one?
1 view (last 30 days)
Show older comments
I want to change the elements of a matrix with a loop command. What I have done is, let’s assume that we have a matrix A=[-1 -5 -2 3;-4 -7 8 -3;-2 -3 -1 5;4 8 2 -3]
[m,n]=size(A);
B=[]
for i = 1:m
I = (i-1)*2;
for j = 1:n
J = (j-1)*2 + 0.5;
if(A(i,j)>0)
B=[B [J;m-I]]
end
end
end
and the results that I get is
B =
6.5000
4.0000
B =
4.5000
2.0000
B =
6.5000
0
B =
0.5000
-2.0000
B =
2.5000
-2.0000
B =
4.5000
-2.0000
How can I take all the numbers of B in one Nx2 matrix ?
1 Comment
Accepted Answer
Azzi Abdelmalek
on 22 Jul 2015
Edited: Azzi Abdelmalek
on 22 Jul 2015
A=rand(4)
[m,n]=size(A);
B=[]
for ii = 1:m
I = (ii-1)*2;
for jj=1:n
J = (jj-1)*2 + 0.5;
if(A(ii,jj)>0)
B=[B;J m-I]
end
end
end
2 Comments
Stephen23
on 22 Jul 2015
Edited: Stephen23
on 22 Jul 2015
When you write this kind of code in MATLAB it will come up with this warning message (which I clicked on to expand the details):
This is because expanding arrays is a really bad idea, and doing this is one of the main ways the beginners slow down their code. See my answer to know how much faster and neater MATLAB code can be, using best practices that do not result in any warnings about writing slow code. Why bother learning bad programming habits that you just have to change later when you can learn how to program properly from the start?
More Answers (1)
Stephen23
on 22 Jul 2015
Edited: Stephen23
on 22 Jul 2015
Instead of slow and painful loops as if MATLAB was some low-level programming language like C, just use simple vectorized code, which is faster and neater:
A = [-1,-5,-2,3; -4,-7,8,-3; -2,-3,-1,5;4,8,2,-3];
[x,y] = find(A.'>0);
X = (x-1)*2 + 0.5;
Y = size(A,1) - (y-1)*2;
B = [X,Y].'
Which displays this in the command window:
B =
6.5000 4.5000 6.5000 0.5000 2.5000 4.5000
4.0000 2.0000 0 -2.0000 -2.0000 -2.0000
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!