Extract only numbers from a cell array.

19 views (last 30 days)
Biswajit Dipan Biswas
Biswajit Dipan Biswas on 7 Feb 2019
Commented: Luna on 7 Feb 2019
Hi,
I have to use the Ybus from the output of OpenDSS in which the admittance is in the format of "21.30045+j-37.934". That too divided into 2 cells in a csv file. In matlab after using the [num_data text_data]=xlsread('filename'); I've got the imaginary entries in cell arrays. I need to extract the numbers only. For example, "-37.934" from the given entry. I've tried "regexp(text,'\d*','match');" but it only takes the numeric entries only, not the negative signs of decimal points. Then using "C=regexp(text,'+j','match');" I got another cell array containting all "+j" only. How can I compare the cells in "text" and "C" arrays and extract only the numbers with their signs excluding "+j"?
Thank you.
  2 Comments
Luna
Luna on 7 Feb 2019
Attach your file so we can see the type of your data.

Sign in to comment.

Answers (2)

Adam Danz
Adam Danz on 7 Feb 2019
Edited: Adam Danz on 7 Feb 2019
Here's a solution that first converts all elements that do not have a 'j' and then converts all elements that do have a 'j'.
% Fake data
t = {'21.30045+j-37.934', '200000', '21.30045+j-37.934', '1000000'};
% Convert
hasJ = contains(t, 'j'); %index of all elements that contain a 'j'
jIdx = regexp(t, 'j'); %index of each string where 'j' occurs
n = nan(size(t)); %allocate output
n(~hasJ) = cellfun(@str2num, t(~hasJ)); %convert elements that do not have a j
% now convert all elements that do have a 'j' but ignore everything before the j.
n(hasJ) = cellfun(@(x,y) str2num(x(y+1:end)), t(hasJ), jIdx(hasJ));
The result ('n') is a vector of class 'double' that is the same size as the input ('t').
n =
-37.934 2e+05 -37.934 1e+06

Luna
Luna on 7 Feb 2019
Your data seems much more complicated than that and has commas inside cells as a char also.
I have removed white spaces, +j s, and commas inside cells between the numbers as a char. I put a space instead of commas then convert it to double.
So that you will get 265x531 double array all numbers.
Here you go:
[num,txt,raw] = xlsread('ieee123_EXP_Y.CSV');
dataCell = cell2mat(cellfun(@(x)str2num(x),cellfun(@(x) strrep(x,',',' '), cellfun(@(x) strrep(x,'+j',''),cellfun(@(x) strrep(x,' ',''),txt,'UniformOutput',false),'UniformOutput',false),'UniformOutput',false),'UniformOutput',false));
  2 Comments
Luna
Luna on 7 Feb 2019
Your welcome :)
Please accept any of those answers which suits you better.

Sign in to comment.

Categories

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

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!