Filter löschen
Filter löschen

Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

How to keep adding a number to a matrix if it occurs several times

1 Ansicht (letzte 30 Tage)
JVM
JVM am 17 Jan. 2017
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
Hey
I would like to add 0.15 to an element in a matrix for each time it occurs in each column. I have this code so far and it works partly
matrix_original=[7,7,4;12,10,10;-3,7,2;10,12,12;10,12,12;10,7,4];
A=size(matrix_original);
% modifying the original matrix
for i=1:A(2)
for j=1:A(1)
matrix_modified(j,i)=matrix_original(j,i);
if length(unique(matrix_modified(:,i)))<length(matrix_modified(:,i))
matrix_modified(j,i)=matrix_modified(j,i)+0.15;
end
end
end
If I run this, my matrix_modified will get the value
7.0000 7.1500 4.0000
12.0000 10.1500 10.0000
-3.0000 7.1500 2.0000
10.0000 12.1500 12.0000
10.1500 12.1500 12.1500
10.1500 7.1500 4.1500
I would like it to show this instead
7.0000 7.0000 4.0000
12.0000 10.0000 10.0000
-3.0000 7.1500 2.0000
10.0000 12.0000 12.0000
10.1500 12.1500 12.1500
10.3000 7.3000 4.1500
Can someone please help me solve this?

Antworten (1)

Guillaume
Guillaume am 17 Jan. 2017
Bearbeitet: Guillaume am 18 Jan. 2017
This would work:
matrix_original=[7,7,4;12,10,10;-3,7,2;10,12,12;10,12,12;10,7,4];
for col = 1:size(matrix_original, 2)
[~, ~, loc] = unique(matrix_original(:, col));
for uloc = 1:max(loc)
toincrease = uloc == loc;
matrix_original(toincrease, col) = matrix_original(toincrease, col) + (0:sum(toincrease)-1).' * 0.15;
end
end
edit: removed the useless find
  2 Kommentare
Jan
Jan am 17 Jan. 2017
Bearbeitet: Jan am 17 Jan. 2017
Or faster without the find:
toincrease = (uloc == loc);
matrix_original(toincrease, col) = matrix_original(toincrease, ...
col) + (0:sum(toincrease)-1).' * 0.15;
Guillaume
Guillaume am 18 Jan. 2017
Yes, of course! Not sure why I thought the find was required.

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by