split cell (containing strings) into cell according to the value of C (column)

조회 수: 1 (최근 30일)
Hi! Is there a way to split cell 'a4' (containing strings) into cell 'a4_new'?
In particular I would like to divide the columns of 'a4' according to the value of C (for example C=6, but it must be valid for C=1:10).
Col = 6;
load a4 %in
load a4_new %out

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 9월 20일
편집: Dyuman Joshi 님. 2023년 9월 20일
load a4 %in
load a4_new %out
%Checking the values of the variables
a4
a4 = 1×33 cell array
Columns 1 through 15 {["307"]} {["314"]} {["318"]} {["320"]} {["323"]} {["329"]} {["331"]} {["333"]} {["334"]} {["335"]} {["336"]} {["338"]} {["340"]} {["341"]} {["342"]} Columns 16 through 30 {["343"]} {["344"]} {["347"]} {["348"]} {["349"]} {["350"]} {["351"]} {["352"]} {["354"]} {["355"]} {["356"]} {["358"]} {["359"]} {["360"]} {["361"]} Columns 31 through 33 {["368"]} {["446"]} {["447"]}
a4_new
a4_new = 6×1 cell array
{1×6 cell} {1×6 cell} {1×6 cell} {1×6 cell} {1×6 cell} {1×3 cell}
Col = 6;
%Split according to the multiples of Col
n = numel(a4);
%Groups to divide the data into
idx = [repelem(Col,1,floor(n/Col)) rem(n,Col)]
idx = 1×6
6 6 6 6 6 3
out = mat2cell(a4,1,idx)'
out = 6×1 cell array
{1×6 cell} {1×6 cell} {1×6 cell} {1×6 cell} {1×6 cell} {1×3 cell}
  댓글 수: 2
Alberto Acri
Alberto Acri 2023년 9월 21일
Thank you for your reply @Dyuman Joshi! I found a (I think solvable) problem in your code. For example with cells 'a2' and 'a9' an 'out' is created with 2 rows (of which the last one is empty).
How can I delete this empty row in case it is generated?
A = importdata("a2.mat");
% A = importdata("a9.mat");
Col = 6;
%Split according to the multiples of Col
n = numel(A);
%Groups to divide the data into
idx = [repelem(Col,1,floor(n/Col)) rem(n,Col)];
out = mat2cell(A,1,idx)';
Dyuman Joshi
Dyuman Joshi 2023년 9월 21일
Yes, the empty row will arise when the number of elements of A is perfect divisible by Col (as the reminder will be 0). I seem to have overlooked it last night.
In that case -
load('a4.mat')
n = numel(a4)
n = 33
%Split according to the multiples of Col
Col = 3;
%Groups to divide the data into
idx = [repelem(Col,1,floor(n/Col)) rem(n,Col)]
idx = 1×12
3 3 3 3 3 3 3 3 3 3 3 0
%% Simply delete the 0 value
idx(idx==0) = [];
out = mat2cell(a4,1,idx)'
out = 11×1 cell array
{1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell}

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by