how to plot data from a cell array that the numbers are type string?

7 views (last 30 days)
Xingda Chen
Xingda Chen on 1 May 2020
Edited: Tommy on 2 May 2020
Hi,
I want to plot some lab data. they are collected in txt file, the data itself in txt looks like this
I want to plot the second colum as y and first colum as x
so I use fopen and textscan
fid = fopen('2_nodes_var_coup.txt');
C = textscan(fid,'%s%s');
fclose(fid)
C{1}(1:5,1) %too see some samples
C{2}(1:5,1)
i found that only the format %s will give the data out as string:
ans = 0
ans =
{'t i m e ' }
{' S t e p ' }
{' X = 5 0 ' }
{' ( R u n : ' }
{' 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 e + 0 0 '}
ans =
{' V ( o s c 1 ) ' }
{' I n f o r m a t i o n : '}
{' ' }
{' 1 / 2 1 ) ' }
{' 6 . 6 0 0 0 0 4 e - 0 7 '}
if i use %f, then there is error
fid = fopen('2_nodes_var_coup.txt');
C = textscan(fid,'%f%f');
fclose(fid)
C{1}(1:5,1)
C{2}(1:5,1)
ans = 0
Index in position 1 exceeds array bounds.
problem is with the %s method i can't plot
fid = fopen('2_nodes_var_coup.txt');
C = textscan(fid,'%s%s');
fclose(fid)
x= C{1}(5:8,1); %so there are only numbers
y= C{2}(5:8,1);
plot(x,y)
ans = 0
Error using plot
Not enough input arguments.
A = str2double(x)
B = str2double(y)
plot(A,B)
ans = 0
Error using plot
Not enough input arguments.
i don't think i am doing the whole thing right, anyone know what would be the right way to do it?
Thanks!

Answers (1)

Tommy
Tommy on 1 May 2020
Note that str2double for the character vectors you have returns NaN:
>> str2double(' 6 . 6 0 0 0 0 4 e - 0 7 ')
ans =
NaN
I believe you are ultimately plotting cell arrays filled with NaN:
>> plot({NaN;NaN},{NaN;NaN})
Error using plot
Not enough input arguments.
(Not that the NaNs are causing the error - the cell arrays are:
>> plot({1;2},{1;2})
Error using plot
Not enough input arguments.
But the fact that you're not getting the correct data is another problem.)
I would try to read the file differently. See if this works:
fid = fopen('2_nodes_var_coup.txt');
C = textscan(fid,'%f%f','HeaderLines',2);
fclose(fid)
x= C{1}(5:8,1); %so there are only numbers
y= C{2}(5:8,1);
plot(cell2mat(x),cell2mat(y))
Or how about readtable?
  2 Comments
Tommy
Tommy on 2 May 2020
No plot shows, or you get an error? There's a difference.
Why convert to a cell array or char array? If you use
T = readtable('2_nodes_var_coup.txt');
what is contained within T? Why not go directly from there, with something like this:
plot(T.Var1, T.Var2)

Sign in to comment.

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by