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

조회 수: 4 (최근 30일)
Xingda Chen
Xingda Chen 2020년 5월 1일
편집: Tommy 2020년 5월 2일
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에서 Labels and Annotations에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by