Info

此问题已关闭。 请重新打开它进行编辑或回答。

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

1 次查看(过去 30 天)
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?

回答(1 个)

Guillaume
Guillaume 2017-1-17
编辑:Guillaume 2017-1-18
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 个评论
Jan
Jan 2017-1-17
编辑:Jan 2017-1-17
Or faster without the find:
toincrease = (uloc == loc);
matrix_original(toincrease, col) = matrix_original(toincrease, ...
col) + (0:sum(toincrease)-1).' * 0.15;

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by