Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

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

1 visualización (últimos 30 días)
JVM
JVM el 17 de En. de 2017
Cerrada: MATLAB Answer Bot el 20 de Ag. de 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?

Respuestas (1)

Guillaume
Guillaume el 17 de En. de 2017
Editada: Guillaume el 18 de En. de 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 comentarios
Jan
Jan el 17 de En. de 2017
Editada: Jan el 17 de En. de 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 el 18 de En. de 2017
Yes, of course! Not sure why I thought the find was required.

La pregunta está cerrada.

Community Treasure Hunt

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

Start Hunting!

Translated by