How can I subtract certain values from a matrix depending on another matrix?

1 次查看(过去 30 天)
Hello, the question may look a bit strange but here is the situation. I have three matrices:
r = [6 10 12;8 5 4;9 8 12]
p = [4 8 13;8 5 5;1 2 0]
d = [5 10 15]'
I want to subtract certain values in a matrix depending on the numbers in the d matrix. So for example 15 is the highest number here and is placed in the third row. Now I want my matlab script to subtract all values in the third row in matrix r from matrix p.
If one of these values in matrix p is zero, then I want my script to subtract another value in that same column, depending on the place of the second highest number in matrix d. For example in p(3,3) is a zero so I want my script to find the second highest value in matrix d, which is 10 in row 2. Now I want the script to subtract r(2,3) from p(2,3)
I just can not come up with a code on how to do this? Is there anyone out there who could help me :)?
  2 个评论
Richard Wolvers
Richard Wolvers 2017-6-4
This is the input for example: r = [6 10 12;8 5 4;9 8 12] p = [4 8 13;8 5 5;1 2 0] d = [5 10 15]'
The desired output would be: result = [4 8 13;8 5 1;-8 -6 0]

请先登录,再进行评论。

采纳的回答

Andrei Bobrov
Andrei Bobrov 2017-6-4
r = [6 10 12;8 5 4;9 8 12]
p = [4 8 13;8 5 5;1 2 0]
d = [5 10 15]'
[~, ord] = sort(d, 'descend');
out = p;
out(ord(1),:) = p(ord(1),:) - r(ord(1),:);
t = p(ord(1),:) == 0;
out(ord(1),:) = out(ord(1),:).*~t;
out(ord(2),t) = p(ord(2),t) - r(ord(2),t)

更多回答(1 个)

Guillaume
Guillaume 2017-6-3
If I understood correctly, this would be one way of doing it:
[~, order] = sort(d, 'reverse');
result = p - r(order(1), :); %requires R016b or later
%in earlier versions: result = bsxfun(@minus, p, r(order(1), :));
rzero = repmat(r(order(2), :), size(p, 1), 1);
result(p == 0) = p(p == 0) - rzero(p == 0);

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by