How can I change the elements of a matrix in new one?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Azzi Abdelmalek
2015-7-22
编辑:Azzi Abdelmalek
2015-7-22
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 个评论
Stephen23
2015-7-22
编辑:Stephen23
2015-7-22
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):
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/183676/image.png)
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?
更多回答(1 个)
Stephen23
2015-7-22
编辑:Stephen23
2015-7-22
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!