split cell in 2 columns

10 次查看(过去 30 天)
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.

采纳的回答

Monika Jaskolka
Monika Jaskolka 2021-7-30
编辑:Monika Jaskolka 2021-7-30
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

更多回答(1 个)

Peter Perkins
Peter Perkins 2021-7-30
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]}

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by