How do I assign variables in matrices? - octave

I can't make matrices with variables in it for some reason. I get following message.
>>> A= [a b ;(-1-a) (1-b); (1+a) b]
error: horizontal dimensions mismatch (2x3 vs 1x1)
Why is it? Please show me correct way if I'm wrong.

In Matlab you first need to assign a variable before you can use it,
a = 1;
b = a+1;
This will thus give an error,
clear;
b = a+1; % ERROR! Undefined function or variable 'a
Matlab does never accept unassigned variables. This is because, on the lowest level, you do not have a. You will have machine code which is assgined the value of a. This is handled by the JIT compiler in Matlab, so you do not need to worry about this though.
If you want to use something as the variable which you have in maths you can specifically express this to matlab. The object is called a sym and the syntax that define the sym x to a variable xis,
syms x;
That said, you can define a vector or a matrix as,
syms a b x y; % Assign the syms
A = [x y]; % Vector
B = A= [a b ;(-1-a) (1-b); (1+a) b]; % Matrix.
The size of a matrix can be found with size(M) or for dim n size(M,n). You can calcuate the matrix product M3=M1*M2 if and only if M1 have the size m * n and M2 have the size n * p. The size of M3 will then be m * p. This will also mean that the operation A^N = A * A * ... is only allowed when m=n so to say, the matrix is square. This can be verified in matlab by the comparison,
syms a b
A = [a,1;56,b]
if size(A,1) == size(A,2)
disp(['A is a square matrix of size ', num2str(size(A,1)]);
else
disp('A is not square');
end
These are the basic rules for assigning variables in Matlab as well as for matrix multiplication. Further, a google search on the error error: 'x' undefined does only give me octave hits. Are you using octave? In that case I cannot guarantee that you can use sym objects or that the syntaxes are correct.

Related

Removing DC component for matrix in chuncks in octave

I'm new to octave and if this as been asked and answered then I'm sorry but I have no idea what the phrase is for what I'm looking for.
I trying to remove the DC component from a large matrix, but in chunks as I need to do calculations on each chuck.
What I got so far
r = dlmread('test.csv',';',0,0);
x = r(:,2);
y = r(:,3); % we work on the 3rd column
d = 1
while d <= (length(y) - 256)
e = y(d:d+256);
avg = sum(e) / length(e);
k(d:d+256) = e - avg; % this is the part I need help with, how to get the chunk with the right value into the matrix
d += 256;
endwhile
% to check the result I like to see it
plot(x, k, '.');
if I change the line into:
k(d:d+256) = e - 1024;
it works perfectly.
I know there is something like an element-wise operation, but if I use e .- avg I get this:
warning: the '.-' operator was deprecated in version 7
and it still doesn't do what I expect.
I must be missing something, any suggestions?
GNU Octave, version 7.2.0 on Linux(Manjaro).
Never mind the code works as expected.
The result (K) got corrupted because the chosen chunk size was too small for my signal. Changing 256 to 4096 got me a better result.
+ and - are always element-wise. Beware that d:d+256 are 257 elements, not 256. So if then you increment d by 256, you have one overlaying point.

Matlab function in fmincon with fixed value

I have a simple model where I want to minimize the RMSE between my dependent variable y and my model values. The model is: y = alpha + beta'*x.
For minimization, I am using Matlab's fmincon function and am struggling with multiplying my parameter p(2) by x.
MWE:
% data
y = [5.072, 7.1588, 7.263, 4.255, 6.282, 6.9118, 4.044, 7.2595, 6.898, 4.8744, 6.5179, 7.3434, 5.4316, 3.38, 5.464, 5.90, 6.80, 6.193, 6.070, 5.737]
x = [18.3447, 79.86538, 85.09788, 10.5211, 44.4556, 69.567, 8.960, 86.197, 66.857, 16.875, 52.2697, 93.971, 24.35, 5.118, 25.126, 34.037, 61.4445, 42.704, 39.531, 29.988]
% initial values
p_initial = [0, 0];
% function: SEE BELOW
objective = #(p) sqrt(mean((y - y_mod(p)).^2));
% optimization
[param_opt, fval] = fmincon(objective, p_initial)
If I specify my function as follows then it works.
y_mod = #(p) p(1) + p(2).*x
However, it does not work if I use the following code. How can I multiply p(2) with x? Where x is not optimized, because the values are given.
function f = y_mod(p)
f = p(1) + p(2).*x
end
Here is the output from a script that has the function declaration:
>> modelFitExample2a
RMS Error=0.374, intercept=4.208, slope=0.0388
And here is code for the above. It has many commented lines because it includes alternate ways to fit the data: an inline declaration of y_mod(), or a multi-line declaration of y_mod(), or no y_mod() at all. This version uses the multi-line declaration of y_mod().
%modelFitExample2a.m WCR 2021-01-19
%Reply to stack exchange question on parameter fitting
clear;
global x %need this if define y_mod() separately, and in that case y_mod() must declare x global
% data
y = [5.0720, 7.1588, 7.2630, 4.2550, 6.2820, 6.9118, 4.0440, 7.2595, 6.8980, 4.8744...
6.5179, 7.3434, 5.4316, 3.3800, 5.4640, 5.9000, 6.8000, 6.1930, 6.0700, 5.7370];
x = [18.3447,79.8654,85.0979,10.5211,44.4556,69.5670, 8.9600,86.1970,66.8570,16.8750,...
52.2697,93.9710,24.3500, 5.1180,25.1260,34.0370,61.4445,42.7040,39.5310,29.9880];
% initial values
p_initial = [0, 0];
%predictive model with parameter p
%y_mod = #(p) p(1) + p(2)*x;
% objective function
%If you use y_mod(), then you must define it somewhere
objective = #(p) sqrt(mean((y - y_mod(p)).^2));
%objective = #(p) sqrt(mean((y-p(1)-p(2)*x).^2));
% optimization
options = optimset('Display','Notify');
[param_opt, fval] = fmincon(objective,p_initial,[],[],[],[],[],[],[],options);
% display results
fprintf('RMS Error=%.3f, intercept=%.3f, slope=%.4f\n',...
fval,param_opt(1),param_opt(2));
%function declaration: predictive model
%This is an alternative to the inline definition of y_mod() above.
function f = y_mod(p)
global x
f = p(1) + p(2)*x;
end
carl,
The second method, in which you declare y_mod() explicitly (at the end of your script, or in a separate file y_mod.m), does not work because y_mod() does not know what x is. Fix it by declaring x global in the main program at the top, and declare x global in y_mod().
%function declaration
function f = y_mod(p)
global x
f = p(1) + p(2)*x;
end
Of course you don't need y_mod() at all. The code also works if you use the following, and in this case, no global x is needed:
% objective function
objective = #(p) sqrt(mean((y-p(1)-p(2)*x).^2));
By the way, you don't need to multiply with .* in y_mod. You may use *, because you are multiplying a scalar by a vector.

Octave - System of differential equations with lsode

here is my problem. I'm trying to solve a system of two differential equations thanks to the two functions below. The part of the code that give me some trouble is the variable "rho". "rho" is a function which values are given from a file and that I tried to put in the the variable rho.
function [xdot]=f2(x,t)
# Parameters of the equations
t=[1:1:35926];
x = dlmread('data_txt.txt');
rho=x(:,4);
beta = 0.68*10^-2;
g = 1.5;
l = 1.6;
# Definition of the system of 2 ODE's :
xdot(1) = ((rho-beta)/g)*x(1) + l*x(2);
xdot(2) = (beta/g)*x(1)-l*x(2);
endfunction
.
# Initial conditions for the two variables :
x0 = [0;1];
# Definition of the time-vector -> (initial time,temporal mesh,final time) :
t = linspace (1, 10, 10000);
# Resolution with the lsode routine :
x = lsode ("f2", x0, t);
# Plot of the two curves :
plot (t,x);
When I run my code, I get the following error:
>> resolution_effective2
error: f2: A(I) = X: X must have the same size as I
error: called from
f2 at line 34 column 9
resolution_effective2 at line 8 column 3
error: lsode: evaluation of user-supplied function failed
error: called from
resolution_effective2 at line 8 column 3
error: lsode: inconsistent sizes for state and derivative vectors
error: called from
resolution_effective2 at line 8 column 3
I know that my error comes from a mismatch of size between some variable but I have been looking for the error for days now and I don't see. Could someone try to give and explain me an effective correction ?
Thank you
The error might come from your function f2. Its first argument x should have the same dimension as x0 since x0 is the initial condition of x.
In your case, whatever you intent to be the first argument of f2 is ignored since in your function you do x = dlmread('data_txt.txt'); this seems to be a mistake.
Then, xdot(1) = ((rho-beta)/g)*x(1) + l*x(2); will be a problem since rho is a vector.
You need to check the dimensions of x and rho.

After one call to myfun, new parametrization does not affect the result, which conforms to the first call

I am new to Octave although I can say I am an expert Matlab user. I am running Octave on a Linux server (Red Hat) remotely through PuTTY, from a windows machine.
I am observing a very strange behavior in Octave. I call myfun(a) which performs as expected giving the sought results. Now, if I run, say, myfun(b) with b!=a, I get again myfun(a). Clear -f does not solve the problem. I need to reboot octave to change the parameters.
What am I doing wrong?
Thanks a lot
Francesco
This is the code for the function I mentioned:
function [a, v, obj, infos, iter] = mle_garch( p )
#{
% this function estimates the GARCH(1,1) parameters
% it is assumed we pass the adjusted price level p
#}
global y = (diff(log(p))-mean(diff(log(p))))*100;
global h = zeros(size(y));
a0 = [var(y)*0.9; 0.8; 0.1];
[a, obj, infos, iter] = sqp(a0, #loglike_garch, [], #loglike_con, [], [], 1000);
v = sqrt(h * 260);
endfunction
function g = loglike_garch( a )
global y h
n = length(y);
h(1) = var(y);
for i = 2 : n,
h(i) = a(1) + a(2) * h(i-1) + a(3) * y(i-1)^2;
endfor
g = 0.5 * ( sum(log(h)) + sum(y.^2./h) ) / n;
endfunction
function f = loglike_con( a )
f = [1;0;0;0] + [0 -1 -1;eye(3)] * a;
endfunction
I'm assuming the myfun you mentioned is mle_garch. The problem is the way you're initializing the global h and v variables (do you really need them to be global?). When you have a piece of code like this
global y = (diff(log(p))-mean(diff(log(p))))*100;
global h = zeros(size(y));
the values of y and h are defined the first time only. You can change their values later on, but this specific lines will never be ran again. Since your code only uses the input argument to define these two variables, the value which you use to run the function the first time will be used every single other time. If you really want to keep those variables global, replace it with the following:
global y;
global h;
y = (diff(log(p))-mean(diff(log(p))))*100;
h = zeros(size(y));
But I don't see any reason to keep them global so just don't make them global.
Also, you mentioned this code worked fine in Matlab. I was under the impression that you couldn't initialize global and persistent variables in Matlab which would make your code illegal in Matlab.

Plotting a 3D function with Octave

I am having a problem graphing a 3d function - when I enter data, I get a linear graph and the values don't add up if I perform the calculations by hand. I believe the problem is related to using matrices.
INITIAL_VALUE=999999;
INTEREST_RATE=0.1;
MONTHLY_INTEREST_RATE=INTEREST_RATE/12;
# ranges
down_payment=0.2*INITIAL_VALUE:0.1*INITIAL_VALUE:INITIAL_VALUE;
term=180:22.5:360;
[down_paymentn, termn] = meshgrid(down_payment, term);
# functions
principal=INITIAL_VALUE - down_payment;
figure(1);
plot(principal);
grid;
title("Principal (down payment)");
xlabel("down payment $");
ylabel("principal $ (amount borrowed)");
monthly_payment = (MONTHLY_INTEREST_RATE*(INITIAL_VALUE - down_paymentn))/(1 - (1 + MONTHLY_INTEREST_RATE)^-termn);
figure(2);
mesh(down_paymentn, termn, monthly_payment);
title("monthly payment (principal(down payment)) / term months");
xlabel("principal");
ylabel("term (months)");
zlabel("monthly payment");
The 2nd figure like I said doesn't plot like I expect. How can I change my formula for it to render properly?
I tried your script, and got the following error:
error: octave_base_value::array_value(): wrong type argument `complex matrix'
...
Your monthly_payment is a complex matrix (and it shouldn't be).
I guess the problem is the power operator ^. You should be using .^ for element-by-element operations.
From the documentation:
x ^ y
x ** y
Power operator. If x and y are both scalars, this operator returns x raised to the power y. If x is a scalar and y is a square matrix, the result is computed using an eigenvalue expansion. If x is a square matrix. the result is computed by repeated multiplication if y is an integer, and by an eigenvalue expansion if y is not an integer. An error results if both x and y are matrices.
The implementation of this operator needs to be improved.
x .^ y
x .** y
Element by element power operator. If both operands are matrices, the number of rows and columns must both agree.