Clear Filters
Clear Filters

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

2 views (last 30 days)
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 Comments
Richard Wolvers
Richard Wolvers on 4 Jun 2017
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]

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 4 Jun 2017
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)

More Answers (1)

Guillaume
Guillaume on 3 Jun 2017
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);

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!