What do I do first? BE A DETECTIVE!
1. Try the command: help commandname (replacing commandname with the subroutine or subprogram you are trying to use).
2. Next, remove the ; from your statements and verify that each step in the calculation is correct.
3. Check that your path is correct (use the set path command or menu item), so that MATLAB can look at the files you want it to.
4. Use clear all to eliminate all traces of variables stored in memory. Sometimes somethingstored there is wrong for your problem (like an extra element in a vector), and was put there in a prior calculation.
How do I check for errors?
1. Remove the ; from your statements and verify that each step in the calculation is correct.
2. Issue the command disp(x) to see the value of x, or just say x; do this in the command window, or for a variable only in a subroutine, do it in the subroutine.
3. ???Undefined function or variable ‘q’. When you see this, Matlab is saying it doesn’t have a value for q. Do step 2. If q is in a subroutine, it has to get in there in one of three ways: (a) as a global variable, defined as global in the calling program (or command window) and the subroutine; (b) set in the subroutine (use step 2 to examine); (c) from the calling arguments (only if it is an independent or dependent variable.
What if the matrices are not the right shape.We can always find the shape of a vector/matrix with
If u is a matrix with 544 rows and 3 columns, size(u) would give [544 3]. If you want to access a whole row, you can use u(:,1), for example.
How can I calculate with matrices?
Suppose we wanted to post-process u. If u(:,3) is T (K) we might want it in C.
u3 = u(:,3) – 273.
This will create a vector u3(i), i=1,…,nlength in which every entry is the value of u(i,3) minus 273. u(:,3) would have nlength entries.
If we wanted u(:,1)/u(:,3), though, we would use
u4 = u(:,1) . / u(:,3)
(Yes, that is a period then divide.) The . / means divide every element of u(:,1) by the element of u(:,3) and make an element of u4(:). You may have to experiment with this since the syntax is not always clear in Matlab. Create vectors/matrices of the appropriate sizes and try your expressions with them.
How can I get rows out of a matrix?
If we have run ode45 to get the result
[t,u] = ode45(…)
where there are 2 or more variables u, we may want to plot them separately. We can transfer them to a vector:
u1 = u(:,1)
u2 = u(:,2)
u3 = u(:,3)
(This is useful if some of the variables are molar flows and some are T or p.) We could also use:
to do the same thing.