Difference between columns, fixed the first column, in a matrix only if values are diferent from 0
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Montserrat Vallcorba Martí
am 10 Nov. 2017
Kommentiert: Montserrat Vallcorba Martí
am 10 Nov. 2017
Hi, I have a 3D-matrix and I want to calculate differences between columns, fixed the first column (this column can have negative values), and the value be positive or zero, i.e., for each 3D dimension calculate: max ( column(i)-column(1), 0 ), but if values in columns i are zero, I don't want to calculate the difference anb the result be zero, i.e.,
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/169411/image.jpeg)
I give you an example:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/169413/image.jpeg)
Any suggestion? Thank you!
0 Kommentare
Akzeptierte Antwort
Guillaume
am 10 Nov. 2017
You've already figured out most of it:
A = cat(3, [10 3 15 12 3; 2 1 4 0 6; -5 0 5 4 12; 7 9 4 0 8], [-3 4 10 3 0; -3 1 0 4 6; 7 2 3 3 8; 8 5 15 5 9]);
result = max(A(:, 2:end, :) - A(:, 1, :), 0); %get difference with column 1, set to 0 if negative
result(A(:, 2:end, :) == 0) = 0 %set to 0 if original value is 0
You could also do it as a one liner but it's a bit more obscure:
result = max(A(:, 2:end, :) - A(:, 1, :), 0) .* (A(:, 2:end, :) ~= 0)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!