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 个评论
采纳的回答
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)
0 个评论
更多回答(1 个)
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!