How can I subtract certain values from a matrix depending on another matrix?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Richard Wolvers
il 3 Giu 2017
Risposto: Andrei Bobrov
il 4 Giu 2017
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 Commenti
James Tursa
il 3 Giu 2017
Can you post a couple of complete examples? I.e., inputs and desired output?
Risposta accettata
Andrei Bobrov
il 4 Giu 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)
0 Commenti
Più risposte (1)
Guillaume
il 3 Giu 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);
0 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!