Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Dyuman Joshi
Dyuman Joshi il 20 Set 2023
Modificato: Dyuman Joshi il 20 Set 2023
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 Commenti
Alberto Acri
Alberto Acri il 21 Set 2023
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 il 21 Set 2023
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}

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by