MATRIX MANUPULATION IF CONDTION NOT WORKING

1 回表示 (過去 30 日間)
SULENDER SAHU
SULENDER SAHU 2022 年 3 月 1 日
コメント済み: SULENDER SAHU 2022 年 3 月 1 日
I have this matrix M:
0 1 2 4
1 5 4 6
3 3 0 1
7 8 0 5
I want to replace the elements in column 4 with 0 corresponding to which elements in column 2 lie between 4 and 9 (in the same row). For example the above matrix should change to :
0 1 2 4
1 5 4 0
3 3 0 1
7 8 0 0
I wrote this code , but it doesen't seem to work .
for i = 1:4
if 4<M(i,2<9
M(i,4)=0;
end
end
  2 件のコメント
Johan
Johan 2022 年 3 月 1 日
Technically the code you wrote can work provided that you divide your logical statement into two combined ones:
M = randi(9,4,4)
M = 4×4
2 4 3 8 5 7 5 4 6 8 6 8 7 5 1 6
M2=M;
for i = 1:4
if 4<M(i,2) && M(i,2)<9
M(i,4)=0;
end
end
M
M = 4×4
2 4 3 8 5 7 5 0 6 8 6 0 7 5 1 0
you can also put a logical matrix in a array variable to change specific data according to your conditions which avoid the need for for loops:
%define value to be changed in colmun 2
conditions = and(M2(:,2)>4,M2(:,2)<9);
%change conditional values in column 4
M2(conditions,4) = 0
M2 = 4×4
2 4 3 8 5 7 5 0 6 8 6 0 7 5 1 0
SULENDER SAHU
SULENDER SAHU 2022 年 3 月 1 日
Thanks for taking the time !!!

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

採用された回答

VBBV
VBBV 2022 年 3 月 1 日
for i = 1:4
if M(i,2)<9 & M(i,2) >4
M(i,4)=0;
end
end
Close the parenthesis and run it.
  1 件のコメント
SULENDER SAHU
SULENDER SAHU 2022 年 3 月 1 日
Thank you very much !!!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by