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

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

回答(1 个)

Tommy
Tommy 2020-5-1
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 个评论
Xingda Chen
Xingda Chen 2020-5-1
编辑:Xingda Chen 2020-5-1
readtable also works.
it also gave a table which i can change it to a cell array or to a char array. but when i try to use str2double it still gives me NaN, nor it will plot...
Tommy
Tommy 2020-5-2
编辑:Tommy 2020-5-2
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)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by