how to rearrange cell array with the grouped sequence

조회 수: 1 (최근 30일)
Shannon
Shannon 2020년 1월 10일
댓글: Shannon 2020년 1월 10일
I have a cell array in this format:
21 3 '1'
31 2 '1 1'
25 1 '2 2 1 1'
How can I rearrange the cell array to:
21 3 1
31 2 1
31 2 1
25 1 2
25 1 2
25 1 1
25 1 1
Thank you!
  댓글 수: 1
Adam Danz
Adam Danz 2020년 1월 10일
편집: Adam Danz 2020년 1월 10일
So within each cell array there are two numeric values and a char array?
Could you show us the actual cell values formatted correctly?
For example,
C =
3×3 cell array
{[21]} {[3]} {'1' }
{[31]} {[2]} {'1 1' }
{[25]} {[1]} {'2 2 1 1'}

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

채택된 답변

Adam Danz
Adam Danz 2020년 1월 10일
C is your input array as I've understood it; D is the output matrix.
% Produce input array
C = {21 3 '1'
31 2 '1 1'
25 1 '2 2 1 1'};
% Convert strings in column 3 to vectors
Cv = cellfun(@(s)str2double(strsplit(s)).',C(:,3),'UniformOutput',false);
% Replicate the rows of C(:,[1,2]) for each value in Cv
C2 = arrayfun(@(i)repmat([C{i,[1,2]}],numel(Cv{i}),1),1:size(C,1),'UniformOutput',false)';
% Combine C2 with Cv values
D = [cell2mat(C2), cell2mat(Cv)];
Result
D =
21 3 1
31 2 1
31 2 1
25 1 2
25 1 2
25 1 1
25 1 1
  댓글 수: 1
Shannon
Shannon 2020년 1월 10일
Many thanks! I am testing it. Will get back to you.

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

추가 답변 (1개)

Stephen23
Stephen23 2020년 1월 10일
>> C = {21,3,'1';31,2,'1 1';25,1,'2 2 1 1'}
C =
[21] [3] '1'
[31] [2] '1 1'
[25] [1] '2 2 1 1'
>> V = cellfun(@(s)sscanf(s,'%f'),C(:,3),'uni',0);
>> Z = [repelem(C(:,1:2),cellfun('length',V),1),num2cell(vertcat(V{:}))]
Z =
[21] [3] [1]
[31] [2] [1]
[31] [2] [1]
[25] [1] [2]
[25] [1] [2]
[25] [1] [1]
[25] [1] [1]

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by