In: Computer Science
Write a script that will first initialize a string variable that will store x and y coordinates of a point in the form ‘x 3.1 y 6.4’. Then, use string manipulating functions to extract the coordinates and plot them. ANS % create a string variable of the form 'x 3.1 y 6.4' % extract the x and y coordinates and plot str = 'x 2.3 y 4.5'; [letter rest] = strtok(str); [x rest] = strtok(rest); [letter rest] = strtok(rest); y = rest(2:end); x = str2num(x); y = str2num(y); plot(x,y,'go')
IN MATLAB I AM TRYING TO USE THIS CODE BUT IS NOT WORKING, may you please use this code and tell what is wrong with it
You have not used comma when using strtok because there are two output from this module. and you need to use str2double in place of str2num.
This is your corrected code
%take the string
str = 'x 2.3 y 4.5';
%extract first word from string and remaining
[letter1, rest] = strtok(str);
%again repeat tha same process
%since second word is numerical coordinate then store it to
variable x
[x, rest] = strtok(rest);
%extract first word from string and remaining
[letter2, rest] = strtok(rest);
%at the last only y coordinate remains
y = rest(2:end);
%convert x to numeical value
x = str2double(x);
%convert y to numeical value
y = str2double(y);
%plot the point
plot(x,y,'go');
%label the x axis
xlabel(letter1);
%label the y axis
ylabel(letter2);
%title to the curve
title(strcat(letter2," vs ",letter1));
%add grid
grid minor;
This is code for second string
%take the string
str = 'x 3.1 y 6.4';
%extract first word from string and remaining
[letter1, rest] = strtok(str);
%again repeat tha same process
%since second word is numerical coordinate then store it to
variable x
[x, rest] = strtok(rest);
%extract first word from string and remaining
[letter2, rest] = strtok(rest);
%at the last only y coordinate remains
y = rest(2:end);
%convert x to numeical value
x = str2double(x);
%convert y to numeical value
y = str2double(y);
%plot the point
plot(x,y,'go');
%label the x axis
xlabel(letter1);
%label the y axis
ylabel(letter2);
%title to the curve
title(strcat(letter2," vs ",letter1));
%add grid
grid minor;
If you have any problem then let me know in comment box and if you like then please rate or give a big thumbs up thank you.