Problem Part 1

MATLAB

Use MATLAB help to find out how you can create a new directory named mynewdir from the MATLAB command line. Then change the working directory the newly-created directory. Then create a MATLAB script in this directory named myscript.m with the following code in it,

% First create an array from -2*pi to 2:pi
x = -2*pi:pi/20:2*pi;

% Calculate |sin(x)|
y = abs(sin(x));

plot(x,y);

Now on MATLAB command line, run the script by calling its name. What do you get? Save the output as a figure and submit it as part of your answer.

Solution Part 1

MATLAB

You can create a new directory and switch the current directory to it using the following commands,

>> mkdir mynewdir
>> cd mynewdir

The script myscript generates a plot of $y$ versus $x$ where $y = |sin(x)|$. In doing so, MATLAB opens a new window called plot window that contains the plot of y as a function of x. Here is the resulting figure,

Problem Part 2

MATLAB

Now change your working directory to the original directory before you created mynewdir directory. Try to run the script myscript you had created again, from MATLAB command line. What do you get? and why?

Solution Part 2

MATLAB

You get an error message like the following on the MATLAB command line,

>> cd mynewdir\
>> myscript
>> cd ..
>> myscript
Undefined function or variable 'myscript'.

And this happens because the script we are trying to run is neither in MATLAB’s working directory nor in any of MATLAB’s search paths. Therefore, MATLAB gives an error, as it cannot find the requested file.

Comments