How can I change the elements of a matrix in new one?

1 回表示 (過去 30 日間)
Ang Vas
Ang Vas 2015 年 7 月 22 日
コメント済み: Ang Vas 2015 年 7 月 23 日
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 件のコメント
Stephen23
Stephen23 2015 年 7 月 22 日
編集済み: Stephen23 2015 年 7 月 22 日
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.

サインインしてコメントする。

採用された回答

Azzi Abdelmalek
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
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):
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?
Ang Vas
Ang Vas 2015 年 7 月 23 日
Thank you a lot for your help and I am sorry for the mess!!!

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by