How to plot large Matlab code
1 view (last 30 days)
Show older comments
I have a function that is almost 300 lines and takes approx. 290 seconds to complete but I want to plot it over a range of 1 to 5. I've tried different things but it always leads to either Matlab R2018a to crash, keep running forever, or just present a blank graph. If anyone has any suggustions, it would be greatly appricated. I was also thinking of trying simulink but I don't know where to start as I have very little experience with it.
4 Comments
dpb
on 1 Dec 2018
Edited: dpb
on 1 Dec 2018
Well, there should be nothing preventing plotting then...what code, specifically, did you run that errors?
fplot(@yourFunc,[1 5])
is about as easy a source code solution as there is...presuming your function accepts one input and returns one output. It undoubtedly will take a while if your function is so compute-intensive as it picks some number of points to plot over in that range--how many isn't really documented.
Otherwise, you'll have to evaluate the function at the points desired and plot...
x=linspace(1,5,10); % try 10 points
y=yourFunc(x); % evaluate the function at those points
plot(x,y) % and plot
Of course, your functions have to be written to accept vector inputs with the above syntax. If that's not the case, then
x=linspace(1,5,10); % try 10 points
y=nan(size(x)); % preallocate, NaN don't plot if error
for i=1:length(x) % iterate over them
y(i)=yourFunc(x(i)); % evaluate the function at those points
end
plot(x,y) % and plot
John D'Errico
on 1 Dec 2018
Use a loop?
That your function is slow running just means you need to either pop open a book while you wait for it to finish, or write more efficient code.
That MATLAB crashes probably means you have a bug in your code somewhere, or a problem of some sort. So fix the bug, or resolve the memory problem that you are creating with multiple calls.
I'm not sure why using Simullink will help, but we are given no information to indicate that Simulink would even be appropriate.
But seriously, what do you really expect someone to say? Write better code. It is a nearly 100% certainty that 300 lines of code written by a relative novice will contain many spots where the code could be massively improved. So learn to use the profile tool, to see where your code is taking time, and what you can improve.
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!