How can I change the elements of a matrix in new one?
3 views (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
Stephen23
on 22 Jul 2015
Doing this in a loop is very poor use of MATLAB. Learn how to write vectorized code and take advantage of the neater, faster solutions to problems like this.
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
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
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!