Convert cell of mixed real and complex numbers into double

3 views (last 30 days)
Convert the following cell array into double,
dd=[ {[1.0000e-03]} {[ 0]}
{[ 0]} {'10.06+28.21i'}]

Answers (2)

Stephen23
Stephen23 on 9 Oct 2023
Edited: Stephen23 on 9 Oct 2023
Without evil STR2NUM:
C = {1.0000e-03,0;0,'10.06+28.21i'}
C = 2×2 cell array
{[1.0000e-03]} {[ 0]} {[ 0]} {'10.06+28.21i'}
M = str2double(C);
X = isnan(M);
M(X) = [C{X}]
M =
0.0010 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 10.0600 +28.2100i

Mathieu NOE
Mathieu NOE on 9 Oct 2023
hello
try this
don't remember where I found this code , probably in the Fex section. many thanks to his creator !
oh, yes, this is it :
I just changed the name of the function to avoid a conflict with the native cell2num function
dd=[ {[1.0000e-03]} {[ 0]}
{[ 0]} {'10.06+28.21i'}];
[outputmat]=another_cell2num(dd)
outputmat =
0.0010 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 10.0600 +28.2100i
%%%%%%%%%%%%%%%%%%%%%%%%%%
function [outputmat]=another_cell2num(inputcell)
% Function to convert an all numeric cell array to a double precision array
% ********************************************
% Usage: outputmatrix=cell2num(inputcellarray)
% ********************************************
% Output matrix will have the same dimensions as the input cell array
% Non-numeric cell contest will become NaN outputs in outputmat
% This function only works for 1-2 dimensional cell arrays
if ~iscell(inputcell), error('Input cell array is not.'); end
outputmat=zeros(size(inputcell));
for c=1:size(inputcell,2)
for r=1:size(inputcell,1)
% original code
% if isnumeric(inputcell{r,c})
% outputmat(r,c)=inputcell{r,c};
% else
% outputmat(r,c)=NaN;
% end
%Works great if you use addition by C Schwalm to the if statement. If statement within the code should now look like :
if isnumeric(inputcell{r,c})
outputmat(r,c)=inputcell{r,c};
elseif isnumeric(str2num(char(inputcell{r,c}))) %addition
outputmat(r,c)=str2num(char(inputcell{r,c})); %addition
else
outputmat(r,c)=NaN;
end
end
end
end

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!