How to append cell arrays with a very specific form

조회 수: 3 (최근 30일)
Piet Jonker
Piet Jonker 2019년 7월 9일
댓글: Piet Jonker 2019년 7월 11일
I have a cell array looking like this
'Rating1' [] [] [] '8'
'Rating1' [] [] '3' []
'Rating1' '2' [] [] []
'Rating1' [] '2' [] []
'Rating2' '5' [] [] []
'Rating2' [] '6' [] []
'Rating2' [] [] '3' []
'Rating2' [] [] [] '7'
'Rating3' '7' [] [] []
'Rating3' [] '7' [] []
'Rating3' [] [] '3' []
'Rating3' [] [] [] '7'
with more than a hundred ratings
I want it to look likes this:
'Rating1' '2' '2' '3' '8'
'Rating2' '5' '6' '3' '7'
'Rating3' '7' '7' '3' '7'
So I have to make a new variable where it appends the score in the columns based on the string in the first column.
I can't really wrap my head around this problem. Can anybody help me perhaps, or give me a push in the right direction?
Thanks alot,
Piet (pronounce as Pete)

채택된 답변

Stephen23
Stephen23 2019년 7월 9일
편집: Stephen23 2019년 7월 9일
As long as your data meet some assumptions:
  • each group contains exactly the same number of rows (four in your example), and
  • each row contains one non-empty data value (in columns 2 - 5).
  • The groups are contiguous.
>> C = {...
'Rating1' [] [] [] '8'
'Rating1' [] [] '3' []
'Rating1' '2' [] [] []
'Rating1' [] '4' [] []
'Rating2' '5' [] [] []
'Rating2' [] '6' [] []
'Rating2' [] [] '3' []
'Rating2' [] [] [] '7'
'Rating3' '7' [] [] []
'Rating3' [] '7' [] []
'Rating3' [] [] '3' []
'Rating3' [] [] [] '7'
};
>> D = permute(reshape(C(:,2:5),4,[],4),[1,3,2]);
>> D(cellfun('isempty',D)) = [];
>> D = [C(1:4:end,1),reshape(D,4,[]).']
D =
'Rating1' '2' '4' '3' '8'
'Rating2' '5' '6' '3' '7'
'Rating3' '7' '7' '3' '7'

추가 답변 (1개)

Jan
Jan 2019년 7월 9일
편집: Jan 2019년 7월 9일
Or:
C = {...
'Rating1' [] [] [] '8'; ...
'Rating1' [] [] '3' []; ...
'Rating1' '2' [] [] []; ...
'Rating1' [] '4' [] []; ...
'Rating2' '5' [] [] []; ...
'Rating2' [] '6' [] []; ...
'Rating2' [] [] '3' []; ...
'Rating2' [] [] [] '7'; ...
'Rating3' '7' [] [] []; ...
'Rating3' [] '7' [] []; ...
'Rating3' [] [] '3' []; ...
'Rating3' [] [] [] '7'};
V = C(:, 2:5);
D = [C(1:4:end, 1), reshape(V(~cellfun('isempty', V)), [], 4)];
Or:
keep = [mod(1:size(C,1), 4).' == 1, ~cellfun('isempty', C(:, 2:5))];
D = reshape(C(keep), [], 5)
  댓글 수: 1
Piet Jonker
Piet Jonker 2019년 7월 11일
This does the trick! Thanks a lot. Matrix indexing has always been tricky for me

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by