Convert cell of mixed real and complex numbers into double
이전 댓글 표시
Convert the following cell array into double,
dd=[ {[1.0000e-03]} {[ 0]}
{[ 0]} {'10.06+28.21i'}]
댓글 수: 1
Dyuman Joshi
2023년 10월 9일
How did you obtain data in this manner?
답변 (2개)
Without evil STR2NUM:
C = {1.0000e-03,0;0,'10.06+28.21i'}
M = str2double(C);
X = isnan(M);
M(X) = [C{X}]
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)
%%%%%%%%%%%%%%%%%%%%%%%%%%
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
카테고리
도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!