Subtracting values in a matrix

Hi, can I just ask you why the code below does not work? I am trying to subtract each value in a row from each other and if the condition is met then add 1 to matrix11(i,j). Apparently there's a problem with matrix10(i,:) expression.
matrix10=[1 7 20; 4 5 6; 7 8 9; 2 5 8];
[zk1, zk2] = size(matrix10);
matrix11=zeros(zk1,zk2);
for i=1:zk1
for j=1:zk2
if (abs(matrix10(i,j) - matrix10(i,:)) >= 2)
matrix11(i,j)=matrix11(i,j)+1;
end
end
end
matrix11 =
0 0 0
0 0 0
0 0 0
0 0 0

回答 (1 件)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017 年 11 月 6 日

0 投票

The problem is with this expression in the if statement:
if abs(matrix10(i,j) - matrix10(i,:)) >= 2
The left hand side is a vector but right side is a scalar -- which means that the condition is only met if all 3 differences exceed 2. What is the actual condition you want to check? If it is whether the total sum of differences exceeds 2, then you need to change the statement to:
if sum(abs(matrix10(i,j) - matrix10(i,:))) >= 2
Or it could be something else depending on what your condition actually is.

5 件のコメント

Jakub Nosek
Jakub Nosek 2017 年 11 月 6 日
Thanks, I want to do it in the way that the condition is met if each of the 3 differences separately exceed 2, so not all of them. So if for example (matrix10(1,1)-matrix10(1,2)) >= 2, then put 1 in the matrix11(1,1) and matrix11(1,2), if also (matrix10(1,1)-matrix10(1,3)) >= 2, then matrix11(1,1) would be 2, matrix11(1,2) would be 1 and matrix11(1,3) would be 1.
Hope you understand what I am trying to say.
Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017 年 11 月 6 日
In that case, this should work:
[zk1, zk2] = size(matrix10);
matrix11=zeros(zk1,zk2);
for i=1:zk1
for j=1:zk2
isTrue = (abs(matrix10(i,j) - matrix10(i,:)) >= 2);
matrix11(i,j) = matrix11(i,j) + sum(isTrue);
end
end
Jakub Nosek
Jakub Nosek 2017 年 11 月 6 日
Cool, thanks, this works fine. But what if I wanted to add another condition and to put the numbers into matrix11 only if both conditions are met. Let's say the second condition is for example abs(matrix12(i,j) - matrix12(i,:)) <=5. Would I need to use IF in this case or do I just define isTrue2?
Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017 年 11 月 6 日
編集済み: Kaushik Lakshminarasimhan 2017 年 11 月 6 日
If matrix10 and matrix12 have the same number of columns, then you won't need an if statement.
You can do something like:
isTrue1 = (abs(matrix10(i,j) - matrix10(i,:)) >= 2);
isTrue2 = (abs(matrix12(i,j) - matrix12(i,:)) <= 5);
isTrue = (isTrue1 & isTrue2); % if both must be true
Jakub Nosek
Jakub Nosek 2017 年 11 月 6 日
Great! Thanks a lot!!

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

カテゴリ

ヘルプ センター および File ExchangeCell Arrays についてさらに検索

質問済み:

2017 年 11 月 6 日

コメント済み:

2017 年 11 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by