Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

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

1 vue (au cours des 30 derniers jours)
JVM
JVM le 17 Jan 2017
Clôturé : MATLAB Answer Bot le 20 Août 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?

Réponses (1)

Guillaume
Guillaume le 17 Jan 2017
Modifié(e) : Guillaume le 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 commentaires
Jan
Jan le 17 Jan 2017
Modifié(e) : Jan le 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 le 18 Jan 2017
Yes, of course! Not sure why I thought the find was required.

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by