Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How can I use global variables for use in a Simulink function?

2,336 views
Skip to first unread message

Alex Ross

unread,
Dec 12, 2009, 9:23:13 PM12/12/09
to
Hiya,

I have a Simulink model in which I need to monitor an output and adjust an input in small steps to maxmise the output.

I have been trying to use a function block so I can write my controller in code. However I need the function to have some memory of previous inputs/outputs and storing these is causing me problems.

When I try to run the simulation it errors saying that Torque3 is undefined. I have preset all variables in the MATLAB workspace and I was under the assumption and variable there could be used in the simulink block function. Or am I wrong?

I have pasted the code I am trying to use below.

[code]
function [y] = controlfunc(u)
%CONTROLFUNC Summary of this function goes here
% Detailed explanation goes here

Torque4 = u;
if (Torque3 == 0)
out = out + 0.01;
bchange4 = 1;
end
if (Torque3 ~= 0)
Tdiff = Torque4 - Torque3;
if (Tdiff >= 0)
if (bchange3 == 1)
bchange4 = 1;
out = out + 0.01;
else
bchange4 = 2;
out = out - 0.01;
end
else
if (bchange3 == 1)
bchange4 = 2;
out = out - 0.01;
else
bchange4 = 1;
out = out + 0.01;
end
end
end
if (out > 20)
out = 20;
end
y = out;

%bchange0 = bchange1;
%bchange1 = bchange2;
%bchange2 = bchange3;
bchange3 = bchange4;
%Torque0 = Torque1;
%Torque1 = Torque2;
%Torque2 = Torque3;
Torque3 = Torque4;
end
[/code]

Arnaud Miege

unread,
Dec 15, 2009, 6:16:38 AM12/15/09
to

"Alex Ross" <alex_...@yahoo.co.uk> wrote in message
news:hg1j6h$i34$1...@fred.mathworks.com...

Are you using an Embedded MATLAB function? Each function has its own
workspace, so you need to pass the parameters you need to the function or
declare the variables as global. Try "doc global" (without the quotes) at
the MATLAB command line for more details.

However, there are a number of problems with your functions, in the sense
that you are doing eqaulity on (presumably) floating-point numbers. Here's
the reason why this isn't a good idea:
http://matlabwiki.mathworks.com/MATLAB_FAQ#Why_is_0.3-0.2-0.1_not_equal_to_zero_.28or_similar.29.3F

You are also not initialising the out variable. Since you are using
Simulink, my recommendation would be to implement this using Simulink
blocks. A hint: you might want to use the switch and/or multiport switch
block, the relational operator block and the saturation block.

HTH,

Arnaud


0 new messages