필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
JVM
JVM 2017년 1월 17일
마감: MATLAB Answer Bot 2021년 8월 20일
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;
Guillaume
Guillaume 2017년 1월 18일
Yes, of course! Not sure why I thought the find was required.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by