필터 지우기
필터 지우기

Data manipulation question, need some help!!

조회 수: 2 (최근 30일)
Xiao Tang
Xiao Tang 2012년 6월 18일
Guys, I really need some help here. I got stuck for a long time.
1. How am I supposed to create a matrix that has two columns, the format of the first one is string, and the second is numerical?
Say a = ['1';'2';'3'], b = [4,5,6], I need to create a matrix like c =
1 4
2 5
3 6
I tried to use c = {a,b}, but the answer is c = [3x1 char] [3x1 double]
2. A =
'15' 3854
'10' 6331
'10' 4324
'20' 3874
'25' 4321
'15' 6835
'10' 3321
'15' 3821
'20' 9324
I need to sum the 2nd column according to the 1st column and create a new matrix. E.g, for '10', I should sum up (6331,4324,3321) , the final result should be
B =
'10' 13976
'15' 10689
'20' 13198
'25' 4321
Any opinion is welcomed!
  댓글 수: 2
Tom
Tom 2012년 6월 18일
If the first column is always numerical, would it be easier to convert the strings to numbers, then convert back to strings when needed?
Xiao Tang
Xiao Tang 2012년 6월 18일
I think that may be a good suggestion. So far I didn't see much difference though.

댓글을 달려면 로그인하십시오.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 6월 18일
A ={...
'15' 3854
'10' 6331
'10' 4324
'20' 3874
'25' 4321
'15' 6835
'10' 3321
'15' 3821
'20' 9324}
[a b b] = unique(A(:,1));
out = [a num2cell(accumarray(b,cat(1,A{:,2})))];
OR
out2 = [str2double(a) accumarray(b,cat(1,A{:,2}))];
  댓글 수: 1
Xiao Tang
Xiao Tang 2012년 6월 18일
Thanks Andrei. It worked perfectly well!
Could you tell me what the cat(1,A{:,2}) does ? Does that convert cell array back to number?
Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 6월 18일
Ta = cellstr(a);
Tb = num2cell(b);
c = [Ta(:), Tb(:)];
  댓글 수: 1
Xiao Tang
Xiao Tang 2012년 6월 18일
Thanks for your reply! It totally solves Question 1.
Is it true that I have to convert those to columns to cell array before I can combine them?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by