split cell in 2 columns

10 vues (au cours des 30 derniers jours)
Dion Theunissen
Dion Theunissen le 30 Juil 2021
I have a 422x1 cell which contains strings as below
0
0
[35.1600000000000,35.1600000000000]
0
0
35.1600000000000
0
0
[35.8200000000000,35.8200000000000]
0
0
35.8200000000000
0
[36.6600000000000,36.6600000000000]
How can i split this cell so that i get 2 different cells. 1 of them is just the first value, the second of them are zeros except when there are 2 values in the string.

Réponse acceptée

Monika Jaskolka
Monika Jaskolka le 30 Juil 2021
Modifié(e) : Monika Jaskolka le 30 Juil 2021
A = {0,0,[35.1600000000000,35.1600000000000],0,0,35.1600000000000, ...
0,0,[35.8200000000000,35.8200000000000],0,0,35.8200000000000,0,[36.6600000000000,36.6600000000000]};
B = zeros(size(A,2), 2);
for i = 1:length(A)
B(i,1) = A{i}(1);
if size(A{i}, 2) > 1
B(i,2) = A{i}(2);
end
end
B = 14×2
0 0 0 0 35.1600 35.1600 0 0 0 0 35.1600 0 0 0 0 0 35.8200 35.8200 0 0

Plus de réponses (1)

Peter Perkins
Peter Perkins le 30 Juil 2021
Use cellfun, two possibilities:
function [val1,val2] = myfun1(x)
val1 = x(1);
if isscalar(x)
val2 = 0;
else
val2 = x(2);
end
end
>> C0 = {1; 2:3; 4:5; 6}
>> [C1,C2] = cellfun(@myfun1,C0,"UniformOutput",false)
>> C12 = [C1 C2]
C12 =
4×2 cell array
{[1]} {[0]}
{[2]} {[3]}
{[4]} {[5]}
{[6]} {[0]}
or
function cellRowOut = myfun2(x)
if isscalar(x)
cellRowOut = {x 0};
else
cellRowOut = {x(1) x(2)};
end
end
>> C12 = cellfun(@myfun2,C0,"UniformOutput",false)
C12 =
4×1 cell array
{1×2 cell}
{1×2 cell}
{1×2 cell}
{1×2 cell}
>> C12 = vertcat(C12{:})
C12 =
4×2 cell array
{[1]} {[0]}
{[2]} {[3]}
{[4]} {[5]}
{[6]} {[0]}

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by