global variable in octave - global

global m = 1;
function p = h()
m
end
h()
I'm trying to run this script, but I get this error:
'm' undefined near line 4 column 3
Say me please, how I can use the variable from functions?

You have to declare the var also global inside the function as described here: https://www.gnu.org/software/octave/doc/interpreter/Global-Variables.html
global m = 1;
function p = h()
global m;
m
endfunction
h()

Related

Matlab: How to write a function that gets an integer n and always returns the result P = 1*1.2*1.4*....*(1+0.2*(n-1))

I am trying to solve a problem that requires writing a function called repeat_prod(n), that gets an integer n and returns the result of the following function:
P = 1*1.2*1.4*....(1+0.2(n-1))
for exemple if n is 6:
repeat_prod(6)
ans = 9.6768
I tried the following:
function P = repeat_prod(n)
for 1:n-1
P = (1+0.2*(n-1));
end
end
But it does not run. How can I get the loop to work?
The logic within your function should be something like below
function P = repeat_prod(n)
P = 1; % initial value for following cumulative products
for k = 1:n
P = P*(1+0.2*(k-1));
end
end
Compact Version
You can also use prod within your function repeat_prod to replace for loop, i.e.,
function P = repeat_prod(n)
P = prod(1 + 0.2*((1:n)-1));
end

How to recall the answer of an if statement in matlab?

I am writing a function, which is suppose to give the result of the following if statement:
s=some scalar
i=some scalar ;
if y(s,i)==L
U(1,i)==0
else disp('Never binding') ;
end
How can I store the "answer" so that the name given to the answer is the output of the function?
for example: ans=R and function R=myfunction(i,s)
Is this possible?
for example if i run my code:
if y(8,1)==L
U(1,1)==0
else disp('Never binding')
end
ans =
X1_2*a - P1_2*X1_2 - X1_2^2*b + X1_2*(LL*(g1_2 + g2_1) + LL*(g1_3 + g3_1)) == 0
or another case:
if y(1,1)==L
U(1,1)==0
else disp('Never binding')
end
Never binding
Here is the code for the complete function:
function R=myIR1(s, n , agent)
x = 'HL'; %// Set of possible types
K = n; %// Length of each permutation
%// Create all possible permutations (with repetition) of letters stored in x
C = cell(K, 1); %// Preallocate a cell array
[C{:}] = ndgrid(x); %// Create K grids of values
y = cellfun(#(x){x(:)}, C); %// Convert grids to column vectors
y = [y{:}];
e=size(y,1);
X = sym('X',[n e], 'positive' );
P = sym('P',[n e], 'positive' );
G=sym('g' , [n,n]) ;
syms c a b ;
s=s;
A = char( zeros(n,2*n) ) ;
for col=1:n
Acol = [col col+1] + (col-1) ;
A(:,Acol) = [ y(s,col)*ones(n,1) y(s,:).' ] ;
end
A1 = reshape( cellstr( reshape(A.',2,[]).' ) , n , n ).' ;
B=A1.*(G+G') ;
B(logical(eye(size(B)))) = 0 ;
for i=1:n
U(i)=[a*X(i,s) - b*(X(i,s))^2 + X(i,s)*(sum(B(:,i).*X(:,s))) - X(i,s)*P(i,s)];
end
agent=agent ;
syms H L ;
i=agent ;
if y(s,i)==L
U(1,i)==0
else disp('Never binding') ;
end
IR is not assigned to anything, I want to assign it to the answer of the if statement..
Thank you
Yes, just assign R to be whatever you want inside the function body. When the function terminates, whatever R was assigned to is the final output that gets sent back to the user.
For example:
function R = myfunction(i,s)
...
...
...
R = ... ;%// Assign the value of R you want here
...
...
end
Then in the MATLAB Command Prompt, you would do:
R = myfunction(i,s);
When calling this function, R will contain whatever you assigned it to be in the function itself. However, you need to make sure that R gets assigned to something before the function terminates. If you don't, then MATLAB will give you an error telling you that you forgot to assign R something as it's expected to be the output.
Given your code, it looks like the main assignment that you want to store is done in the if statement at the end of your code. You're actually not storing that assignment to a variable. In particular:
if y(s,i)==L
U(1,i)==0
else disp('Never binding') ;
end
If you don't assign a variable to something, it automatically gets stored in a variable called ans, which is what you're echoing to the command prompt as you're not placing a semi-colon in front of the U(1,i) == 0 statement. I believe you want to take this output and assign it to R as R is the final output variable you want, so just do this. Note that your output variable is called IR and not R so make sure you change the output variable to R in the function:
if y(s,i)==L
R = U(1,i) == 0;
else disp('Never binding') ;
end
Place a semi-colon at the end of the statement so it doesn't unnecessarily echo the output to the screen.

What does this MATLAB class to and why isn't it working on my PC?

The very first one in this documentation:
http://www.mathworks.com/help/matlab/matlab_oop/getting-familiar-with-classes.html
The class is:
classdef BasicClass
properties
Value
end
methods
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
end
end
When I run it this way
a = BasicClass
a.Value = pi/3;
It works fine and does what it should but this piece of code
a = BasicClass(pi/3);
Gives the following error:
"Error using round
Too many input arguments."
What does it mean? (I'm using R2014a) Is it stupid to use oop in Matlab? LOL
Your error message doesn't look correct compared with the code, whichever your missing a class constructor (as is mentioned at the half way down the help link):
classdef BasicClass
properties
Value
end
methods
% Class constructor -> which you can pass pi/3 into.
function obj = BasicClass ( varargin )
if nargin == 1
obj.Value = varargin{1};
end
end
% Your Methods
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
end
end

Undefined function or variable

I have a simple function as below:
function dz = statespace(t,z)
dz = A*z + B*k*z
end
My main script is :
clear all;close all;format short;clc;
% step 1 -- input system parameters
% structure data
M1 = 1; M2= 1; M3= 1; %Lumped Mass(Tons)
M= diag([M1,M2,M3]);
k(1)= 980; k(2)= 980; k(3)= 980; %Stiffness Coefficient(KN/M)
K = zeros(3,3);
for i=1:2
K(i,i)=k(i)+k(i+1);
end
K(3,3)=k(3);
for i=1:2
K(i,i+1)=-k(i+1);
end
for i=2:3
K(i,i-1)=-k(i);
end %Stiffness Matrix(KN/M)
c(1)= 1.407; c(2)= 1.407; c(3)= 1.407; %Damping Coefficient(KN.sec/M)
C = zeros(3,3);
for i=1:2
C(i,i)=c(i)+c(i+1);
end
C(3,3)=c(3);
for i=1:2
C(i,i+1)=-c(i+1);
end
for i=2:3
C(i,i-1)=-c(i);
end %Damping Matrix(KN.sec/M)
A = [zeros(3) eye(3);-inv(M)*K -inv(M)*C]
H = [1;0;0]
B = [0;0;0;inv(M)*H]
k = [-1 -1 -1 -1 -1 -1]
t = 0:0.004:10;
[t,z] = ode45(statespace,t);
When I run my main script it comes with following error:
Undefined function or variable 'A'.
Error in statespace (line 2)
dz = A*z + B*k*z
As you can see I defined A in main script. Why this problem happening?
There multiple things wrong with your code. First, you need to supply the values of A and B to your function but as you are invoking it (incorrectly without the # and additional parameter y0 as I commented below) in the toolbox ode45, you have to keep just two parameters so you cannot supply A and B as additional parameters. If you define A and B within your function or share them via global variables you will get further. However, as noted below the definitions don't seem to be correct as A * z and B * k * z don't have the same dimensions. z is a scalar so B * k needs to be same size and shape as A which currently it is not.
Edit from:
As Jubobs suggested change your function's parameters to include A, B and k. Also you don't need t as it is never used in the function. So:
function dz = statespace(A, B, k, z)
dz = A*z + B*k*z
end
As others have pointed out, A, B and k are not defined in the function workspace, so you either need to define them again (ugly, not recommended), declare them as global variables (slightly better, but still not good practice), or pass them as arguments to your function (the better solution). However, because you then want to use the function with ode45, you need to be a bit careful with how you do it:
function dz = statespace(t,z,A,B,k)
dz = A*z + B*k*z
end
and then the call to ode45 would like this:
[t,z] = ode45(#(t,z)statespace(t,z,A,B,k),[0 Tf],z0); % where Tf is your final time and z0 your initial conditions
See Error using ode45 and deval for a similar problem.

nlfilter: Choosing nested subfunctions?

The syntax for nlfilter in MATLAB is:
B = nlfilter(A, [m n], fun)
I am considering creating a M-File with several subfunctions to be called using test function here; i.e., I wanted a choice such that each time I can choose what subfunction gets called under fun.
% Main Function
function test
B = nlfilter(A, [m n], fun)
% Subfunction 1
function sub1
.......
% Subfunction 2
function sub2
.......
% Subfunction 3
function sub3
.......
Will it be possible to generalize fun in such a way that I can call either sub1 or sub2 or sub3 from test.
EDIT
My function:
function funct(subfn)
clc;
I = rand(11,11);
ld = input('Enter the lag = ') % prompt for lag distance
fh = {#dirvar,#diagvar};
feval(fh{subfn});
A = nlfilter(I, [7 7], subfn);
% Subfunction
function [h] = dirvar(I)
c = (size(I)+1)/2
EW = I(c(1),c(2):end)
h = length(EW) - ld
end
% Subfunction
function [h] = diagvar(I)
c = (size(I)+1)/2
NE = diag(I(c(1):-1:1,c(2):end))
h = length(NE) - ld
end
end
When I run funct(1) now this is the output with error:
Enter the lag = 1
ld =
1
??? Input argument "I" is undefined.
Error in ==> funct>dirvar at 12
c = (size(I)+1)/2
Error in ==> funct at 6
feval(fh{subfn});
I am puzzled as to what is the problem now?
If you know the name of the subfunction, you can use str2func:
Change the test function to accept a string which holds the subfunction name:
function test (subfunNm)
And call nlfilter like this:
B = nlfilter(A, [m n], str2func (subfunNm));
Now you can call test:
test ('sub1')
etc.
EDIT
In the case of nested functions, you can hold a cell array of the function handles, and pass in an index (instead of a string):
function test(fnInd)
fh = {#f1,#f2,#f3};
feval(fh{fnInd});
function f1
disp('f1')
end
function f2
disp('f2')
end
function f3
disp('f3')
end
end
And call it using test (1) etc.
Take a look at str2func and/or function handles.
I'd personally stay away from strings to pass functions, but you might just need to use that.