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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!