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

1 vue (au cours des 30 derniers jours)
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 commentaires
James Tursa
James Tursa le 3 Juin 2017
Can you post a couple of complete examples? I.e., inputs and desired output?
Richard Wolvers
Richard Wolvers le 4 Juin 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]

Connectez-vous pour commenter.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 4 Juin 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)

Plus de réponses (1)

Guillaume
Guillaume le 3 Juin 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);

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by