Matlab beginner: function that iterates a matrix - matlab

I am a beginner of Matlab. I am trying to run this function but there seem to be a syntax error that I cannot understand. The source code is the following.
function print_trace(x)
for rowi=1:size(x,1),
for coli=1:size(x,2),
disp(x(rowi,coli))
end
end
The error encountered is the following:
??? Input argument "x" is undefined.
Error in ==> print_trace at 2
for rowi=1:size(x,1),
Any ideas?
EDIT: here is a screenshot: http://imgur.com/pwPhzhh
EDIT 2:
Trying to see if there are multiple copies running:
>> which('print_trace')
C:\Users\stablum\Dropbox\cm\print_trace.m
EDIT: solution of the problem :)
it seems that I solved the problem, my mistake was running ("play" button) the file of the function instead of just calling the function (which will load the file automatically). I still don't understand why there was this error when the file is run, but at least my problem is solved.

I suppose it is because of the way you call the function.
The error indicates that you don't give the required parameter x. Especially, you seem t o call the function with
print_trace()
or
print_trace
or
print_trace(empty_cell{:})
which leads to the effect that there is no value to be assigned to x.

Related

Matlab Parallel Computing with Simulink Model

I'm working on a project in which parallel computing would be a huge advantage. The project simulates multiple Simulink models. I did the simulation with a normal for-Loop, but since it takes days to simulate I decided to try the "parfor"-Loop.
But that's where the problem begins. First I'll give you pictures of my code, the workspace and the Simulink-part which is causing me problems:
Here's my code:
apool = gcp('nocreate');
if isempty(apool)
apool = parpool('local');
end
wpath = pwd;
parfor k = 1:number_of_models
load_system(strcat(wpath,'\Models_Folder\',House(k).model_name));
set_param(House(k).model_name, 'Stoptime', num2str(foreruntime));
set_param(House(k).mask_name, 'Data_contr', num2str(controlvector(k)));
set_param(House(k).mask_name, 'Data_cons', strcat('GlobalData(',num2str(k),').consume.',MaskParam(k).consume_input))
SimOut(k) = sim(House(k).model_name);
end
delete(apool);
The confusing thing is if i delete the column:
SimOut(k) = sim(House(k).model_name);
the code just works fine -> the modelparameters are set in a parfor loop
but if I don't delete the column the following error appears:
Error using Forerunsimple (line 9)
Error evaluating parameter 'Data_cons' in 'model_house_14/House'
Caused by:
Error using parallel_function>make_general_channel/channel_general (line 907)
Error evaluating parameter 'Data_cons' in 'model_house_14/House'
Error using parallel_function>make_general_channel/channel_general (line 907)
Undefined variable "GlobalData" or class "GlobalData".
As you can see in the picture the variable "GlobalData" is defined in the workspace. So in my opinion it should work. Obviously it doesn't. Do you have any idea what could be the problem?
you may want to see this question, IMHO, it is related, and could in fact be the same problem:
MATLAB: What happens for a global variable when running in the parallel mode?
There a workspace global variable appears to be empty, even if it was defined.
user Edric provides a link, and a short explanation, that global variables are not passed to workers (for instance simulink running as parallel).
The link is to this blog entry: "Getting parfor loops up and running":
http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/

Error using A3_4 (line 6) Not enough input arguments

This is my code:
%Activity 3.4 An object is thrown vertically with a speed vo reaches at
%height h at a time t.
function t = time(h,vo,g)
t = roots([0.5*g,-vo,h])
%Testing the function
test = time(100,50,9.81)
I've looked through different solutions but still can't figure out why I keep getting this error.
The error is happening on the line t = roots([0.5*g,-vo,h]).
Three comments:
You are probably pushing the Play button in the MATLAB editor. Don't do that. Forget that it even exists. Define h, vo and g in your Command Prompt, then do t = time(h, vo, g); in the Command Prompt. Again, do not push the Play button.
Make sure your working directory is set to where you defined the function time. MATLAB can't find this function that you defined. If you don't know how to do that, check out this from MathWorks: http://www.mathworks.com/help/matlab/ref/cd.html
Your error says it's trying to use a file called A3_4, yet your function is called time. In other words, It looks like you called your file A3_4.m yet it needs to be called time.m. Make sure it's in a file called time.m, then try again. That's one of MATLAB's cardinal rules. When you define a function, the function name and file name need to match.
Do all of those three steps in order, and you will be laughing and singing like these guys below:
(source: kym-cdn.com)

Variable Declaration with the Presence of Nested Functions

Someone on /r/matlab asked me a really interesting question a few days ago related to a Flappy Bird clone submitted to the MATLAB FEX. The poster noticed that if you open the main .m file, stop it in the debugger on the first line, and run a whos(), you see a bunch of variables before they are explicitly defined by the function.
The first thing that I noticed in the editor was the syntax highlighting indicating the presence of nested functions. At a glance, it seems like the variables returned by the whos() are only those that will be defined at some point in the scope of the base function.
You can recreate this with a simpler example:
function testcode
asdf = 1;
function testing
ghfj = 2;
end
end
If you set a breakpoint on the first line and run a whos(), you get
Name Size Bytes Class Attributes
ans 0x0 0 (unassigned)
asdf 0x0 0 (unassigned)
I couldn't seem to find anything explaining this behavior in the documentation for nested functions or related topics. I am not a computer scientist and my programming knowledge is limited to MATLAB and a very small sprinkling of Python. Can anybody explain what is going on? Does it have something to do with how MATLAB compiles the code at run time?
The workspace of a function with nested function is protected. When the function is called, Matlab has to analyze the code to determine which variables are in scope at what part of the function. Remember, variables that are declared in the main function and that are used in a nested function are passed by reference, and can be modified within the nested function even if not explicitly declared as input or output.
To avoid messing up any of the nested functions, and possibly to help speed things up, Matlab does not allow assigning any additional variables to the workspace of that function. For example, if you stop the execution of the code at line 1, and then try assigning a value to a new variable klmn, Matlab will throw an error. This can be a bit frustrating for debugging, but you can always assign ans, fortunately.

Can I view persisten variables in Matlab?

I have a problem that I'm having a hard time even framing for this question's title.
I have a library that calculates the properties of refrigerants. For example, you give pressure and enthalpy, and it tells you the temperature. That library is coded in Fortran with a mex file to interface with Matlab. Now, I am 100% sure that library is thoroughly debugged (it was coded by people much smarter than me, and has been used for almost a decade). The problem is definitely in how I call it.
And that problem is this. I call the library from a StartFcn callback (a .m script file) in a subsystem of a simulink model. The first time I run this model, it runs perfectly. The values I'm sedning to the function are therefore correct. The second time I run it, however, it crashes. The inputs both times are exactly the same.
Also, if I do a clear all between the two runs, then there is no crash. But if I do only clearvars or clear, I still get a crash. When I debug and look at the variables being passed in the function call, they are valid and the same both times.
Does someone have any experience with this, or can advise me on what I might be doing wrong? Is there something persisting within the function call that only clear all can remove and not clear? Save My Soul!
Yes, persistent variables can be declared by the persistent keyword.
If you want to clear only those, try
clear StartFcn
to clear all variables of the function StartFcn. A quote from the documentation:
If name is a function name, then clear name reinitializes any persistent variables in the function.
A quick thing to try would be clear mex inbetween simulations - this should clear all the mex code from matlab.
Other questions to think about..
Can you call the fortran interface directly from the matlab command line two times in a row?
I believe that using a m-file sfunction to call fortran in simulink is quite inefficient. Possibly consider writing your own fortran or C sfunction to interface to the code and compile in directly?
in case you're using LoadLibrary to load fortran code compiled into a dll, are you calling FreeLibrary in the mdlTerminate function?
Hope some of this helps.
I would try to put a clear all inside the function that you are calling in the StartFcn Callback.
So let's say your function is:
function [out] = nameoffunction(a,b,c)
%do calculation with a,b,c
d = a + b + c;
%output out
out = d;
assignin('base','out',d)
clear all
And you can call the function:
nameoffunction(a,b,c)
Let me know if it changes something. If this works, you could try other clear command but inside the function.

How can matlab be unable to find an anonymous function?

I get a strange error when running my script:
Unable to find function #(x) exp(x) within H:\blabla\myClass.m.
when I debug I get:
34 b=myAnonymousFunction(a)
K>> myAnonymousFunction(3)
Unable to find function #() exp(x) within HH:\blabla\myClass.m.
K>> class(myAnonymousFunction)
ans =
function_handle
A minimal example I was trying to produce worked fine.
Do You have any Idea where the error comes from and what it means?
Because he obviously can find the definition of insanity...ahh... myAnonymousFunction. Is it just a bug? I read something on matlabcentral but its 7 Years old and doesn't give an explanation.
Further explanation:
I'm running MATLAB 2012 b under Windows 8 64 bit. The source files were originally written under a 64 bit Linux.
I don't think it's relevant but myAnonymousFunction is a parameter to a function in myClass and stored within a cell array. So it's like this:
file myClass.m:
classdef myclass < handle
properties
x=1337;
myAnonymousFunctions;
end
methods
function new = myClass(myAnonymousFunctions)
new.myAnonymousFunction=myAnonymousFunction
end
function show(o)
disp(myAnonymousFunction{1}(o.x));
end
end
end
and gets called like
myMyclass = myClass({#(x)exp(x)})
myMyClass.f();
Possible Workaround: restart Matlab.
After restarting MATLAB the Problem didn't occur ... so far.
I guess buggy ML debugger was buggy.
I also received the same error when using an anonymous function in a class. The function was stored as a field inside a Matlab class as:
dataBlockObj.processStream(dataBlockObj.activeProcessStreamIndex).func=#(x) x;
and I had been debugging the code, however the error occurred while I was running the code on the command line without any breakpoints set. The solution for me was also restarting Matlab. I was running Matlab 2012b 64bit on a Windows 2008 Server.