필터 지우기
필터 지우기

concatenating more values on a matrix

조회 수: 1 (최근 30일)
Alexandru Miculescu
Alexandru Miculescu 2015년 3월 21일
편집: Stephen23 2015년 3월 21일
Hi everyone! I've been struggling with a simple problem for a while but i could not figure it out how to do it. What i want to do is that if it happens to be the same value more then once on the first column is to eliminate the others and add their second column together. For the example in the picture i want:
6 - 0.03;
8 - 0.05;
5 - 0.06;
3 - 0.03;
if true
% v = fix(10*rand(10))
heads = 1:10;
probab = 1:10;
count = 0;
for i = 1:10
heads(i) = v(i);
for j = 1:10
if ( v(i,j) == heads(i) )
count = count + 1;
end
end
probab(i) = count;
count = 0;
end
X = vertcat(heads, probab/100)
end

채택된 답변

Stephen23
Stephen23 2015년 3월 21일
편집: Stephen23 2015년 3월 21일
You can do this quite easily using unique and accumarray. In fact solving this kind of problem is exactly what accumarray is intended for:
>> A = [6,3,8,5,3,9,8,5,6,5;0.01,0.02,0.03,0.01,0.01,0.03,0.02,0.02,0.02,0.03];
>> [B,~,idx] = unique(A(1,:));
>> [B.',accumarray(idx(:),A(2,:))]
ans =
3 0.03
5 0.06
6 0.03
8 0.05
9 0.03
If you have a newer MATLAB version you can use the 'stable' option as well, which might give you the output order you want:
>> [B,~,idx] = unique(A(1,:),'stable');
>> [B.',accumarray(idx(:),A(2,:))]
ans =
6 0.03
3 0.03
8 0.05
5 0.06
9 0.03

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by