So I have a script which executes coordinate descent algorithm for a quadratic function. I also created a function to make different plots, this is the first part I add. The code executes without any error, but I'm unable to see the surface, I can only see the path of my algorithm descending.
The function updater:
function [f,delta] = fcalculator (Q, x0, c, p)
a = size(x0);
n = a(2);
f = (x0*Q*x0') - (c * x0') + p ;
delta = (Q*x0')- c';
endfunction
The main program:
clear all, close all,
fprintf(' 0 = probleme specifique \n 1 = probleme random \n 2 = Tapez votre propre probleme\n')
choix = input ('Choix : ');
n=0;
if (choix == 0)
[Q, x0, c, p] = quadfunctiongenerator(n,choix)
maxiter = input ( 'Nombre de iterations :');
[x, z] = coordinatedescent(Q,c,p,x0,maxiter);
visualizer(x, z, Q, c, p);
else
n = input ('Choix des dimensions: n = ');
[Q, x0, c, p] = quadfunctiongenerator(n,choix);
endif
The module to create the plots:
function [x1, x2, fuf] = visualizer(x, z, Q, c, p)
clf;
% Pour le cas le plus general, apres on fera:
% iters = 1:size(x)(1);
% plot(iters,x(:,1))
if size(x)(2)
% Afficher les iterees:
plot3(x(:,1), x(:,2), z)
hold on;
% fcalculator (Q, x0, c, p)
% Display the function's surface:
%% Calculate limits:
x1_low = x(1,1);
x1_hi = x(size(x)(1),1) + x1_low;
x2_low = x(1,2);
x2_hi = x(size(x)(1),2) + x2_low;
% Resolution will be the number of points:
resolution = 100;
x1 = (linspace(x1_low, x1_hi, resolution))';
x2 = (linspace(x2_low, x2_hi, resolution))';
f = [];
[xx, yy] = meshgrid (x1, x2);
for i=1:resolution
for j=1:resolution
[_tmp, _] = fcalculator(Q, [x1(i),x2(j)], c, p);
f(i,j) = _tmp;
endfor
endfor
_string = sprintf('%d ', size(x1));
fprintf('Answer: %s\n', _string);
_string = sprintf('%d ', size(x2));
fprintf('Answer: %s\n', _string);
_string = sprintf('%d ', size(f));
fprintf('Answer: %s\n', _string);
mesh(x1, x2, f);
endif
endfunction
I believe the problem is my call to mesh() as I didn't use the variables xx and yy created when calling meshgrid() but the dimensions of x1, x2 and f are the same as those of the variables used to create the famous sombrero plot:
tx = ty = linspace (-8, 8, 41)';
[xx, yy] = meshgrid (tx, ty);
r = sqrt (xx .^ 2 + yy .^ 2) + eps;
tz = sin (r) ./ r;
mesh (tx, ty, tz);
Am I supposed to create f as an elementwise operation as shown in the sombrero plot example?
Is there any octave function to help me create the surface of the function I am optimizing?
I found the problem. The call to mesh() was correct. The problem was the definition of the boundaries.
x1_low = x(1,1);
x1_hi = x(size(x)(1),1) + x1_low;
x2_low = x(1,2);
x2_hi = x(size(x)(1),2) + x2_low;
Yielded x1_low == x1_hi. The code was replaced with:
x1_low = min(x(:,1));
x1_hi = max(x(:,1));
x2_low = min(x(:,2));
x2_hi = max(x(:,2));
Which yielded the desired surface.
Related
This question already has an answer here:
MATLAB curve fitting - least squares method - wrong "fit" using high degrees
(1 answer)
Closed 3 years ago.
Hello my question is about curve tiffing of P3(x) I write my code with using polyfit and polyval functions but I need to make it without using these functions.
this is my code that I wrote
n=input('Enter a value: ');
if(n<3)
fprintf('Enter a different value larger than 3')
end
if(n>=3)
x = 1:n;
y = -0.3*x + 2*randn(1,n);
[p,S] = polyfit(x,y,3);
[y_fit,delta] = polyval(p,x,S);
plot(x,y,'bo')
hold on
plot(x,y_fit,'r-')
title('Linear-Fit Output')
legend('Data','Linear Fit')
end
this is code that I write it is working but I am suppose to write it without using polfite and polyval functions
Without Using syms
y = a0*x^0 + a1*x^1 + a2*x^2 + a3*x^3
For n data point --> y = X*a
where
X = [x1^0 , a1*x1^1, a2*x1^2 , a3*x1^3; x2^0 , a1*x2^1, a2*x2^2 , a3*x2^3;...;xn^0 , a1*xn^1 , a2*xn^2 , a3*xn^3 ]
and a = [a0, a1, a2, a3]; y = [y1, y2, ..., yn]
a is computed as follow
y = X*a ---> a = X\y
The code is as follows
n is given
x = 1:n;
y = -0.3*x + 2*randn(1,n);
x0 = ones(n, 1);
x1 = x';
x2 = (x.^2)';
x3 = (x.^3)';
X = [x0 x1 x2 x3];
a = X\(y');
f =#(t)a(1) + a(2).*t + a(3).*(t.^2)+ a(4).*(t.^3);
Use least square method to find best fit cubic polynomial
n=input('Enter a value: ');
if(n<3)
fprintf('Enter a different value larger than 3')
else
x = 1:n;
y = -0.3*x + 2*randn(1,n);
% Cubic regression
syms a0 a1 a2 a3
yq = a0 + a1.*x + a2.*(x.^2) + a3.*(x.^3) ;
rq = yq - y;
f = sum(rq.^2);
fa0 = diff(f,a0);
fa1 = diff(f,a1);
fa2 = diff(f,a2);
fa3 = diff(f,a3);
sol = solve(fa0 == 0, fa1 == 0, fa2 == 0, a0, a1, a2, a3);
a0 = sol.a0;
a1 = sol.a1;
a2 = sol.a2;
a3 = sol.a3;
% Cubic Regression Curve Function
f =#(t)a0 + a1.*t + a2.*(t.^2)+ a3.*(t.^3);
% Plot Data and Cubic Regression Curve
h = figure(1);
% Data
plot3 = scatter(x, y, 100, '+', 'MarkerEdgeColor', 'red', 'linewidth', 5);
hold on
% cubic Regression Curve
xx = linspace(0,n,100);
plot4 = plot(xx, f(xx), 'linewidth', 5);
[~,b] = legend([plot3 plot4],{'Real Data','Cubic Regression'}, 'FontSize',30);
set(findobj(b,'-property','MarkerSize'),'MarkerSize',30);
xlabel('x-axis','color', 'k', 'fontSize', 25)
ylabel('y-axis', 'color','k', 'fontSize', 25)
hYLabel = get(gca,'YLabel');
set(hYLabel,'rotation',0,'VerticalAlignment','middle', 'HorizontalAlignment','right')
grid on
grid minor
set(gca,'FontSize',20)
set(get(h,'CurrentAxes'),'GridAlpha',0.8,'MinorGridAlpha',0.5);
xticks(x);
title('Cubic Regression', 'color', 'r');
whitebg('w');
end
n = 5
n = 20
I have always used R, so I am quite new to Matlab and running into some troubleshooting issues. I am running some code for a tensor factorization method (available here: https://github.com/caobokai/tBNE). To start I tried to run the demo code, which generates simulated data to run the method with, which results in the following error(s):
Error using feval
Undefined function or variable 'Sfun'.
Error in OptStiefelGBB (line 199)
[F, G] = feval(fun, X , varargin{:}); out.nfe = 1;
Error in tbne_demo>tBNE_fun (line 124)
S, #Sfun, opts, B, P, X, L, D, W, Y, alpha, beta);
Here is the block of code I am running:
clear
clc
addpath(genpath('./tensor_toolbox'));
addpath(genpath('./FOptM'));
rng(5489, 'twister');
m = 10;
n = 10;
k = 10; % rank for tensor
[X, Z, Y] = tBNE_data(m, n, k); % generate the tensor, guidance and label
[T, W] = tBNE_fun(X, Z, Y, k);
[~, y1] = max(Y, [], 2);
[~, y2] = max(T{3} * W, [], 2);
fprintf('accuracy %3.2e\n', sum(y1 == y2) / n);
function [X, Z, Y] = tBNE_data(m, n, k)
B = randn(m, k);
S = randn(n, k);
A = {B, B, S};
X = ktensor(A);
Z = randn(n, 4);
Y = zeros(n, 2);
l = ceil(n / 2);
Y(1 : l, 1) = 1;
Y(l + 1 : end, 2) = 1;
X = tensor(X);
end
function [T, W] = tBNE_fun(X, Z, Y, k)
% t-BNE computes brain network embedding based on constrained tensor factorization
%
% INPUT
% X: brain networks stacked in a 3-way tensor
% Z: side information
% Y: label information
% k: rank of CP factorization
%
% OUTPUT
% T is the factor tensor containing
% vertex factor matrix B = T{1} and
% subject factor matrix S = T{3}
% W is the weight matrix
%
% Example: see tBNE_demo.m
%
% Reference:
% Bokai Cao, Lifang He, Xiaokai Wei, Mengqi Xing, Philip S. Yu,
% Heide Klumpp and Alex D. Leow. t-BNE: Tensor-based Brain Network Embedding.
% In SDM 2017.
%
% Dependency:
% [1] Matlab tensor toolbox v 2.6
% Brett W. Bader, Tamara G. Kolda and others
% http://www.sandia.gov/~tgkolda/TensorToolbox
% [2] A feasible method for optimization with orthogonality constraints
% Zaiwen Wen and Wotao Yin
% http://www.math.ucla.edu/~wotaoyin/papers/feasible_method_matrix_manifold.html
%% set algorithm parameters
printitn = 10;
maxiter = 200;
fitchangetol = 1e-4;
alpha = 0.1; % weight for guidance
beta = 0.1; % weight for classification loss
gamma = 0.1; % weight for regularization
u = 1e-6;
umax = 1e6;
rho = 1.15;
opts.record = 0;
opts.mxitr = 20;
opts.xtol = 1e-5;
opts.gtol = 1e-5;
opts.ftol = 1e-8;
%% compute statistics
dim = size(X);
normX = norm(X);
numClass = size(Y, 2);
m = dim(1);
n = dim(3);
l = size(Y, 1);
D = [eye(l), zeros(l, n - l)];
L = diag(sum(Z * Z')) - Z * Z';
%% initialization
B = randn(m, k);
P = B;
S = randn(n, k);
S = orth(S);
W = randn(k, numClass);
U = zeros(m, k); % Lagrange multipliers
%% main loop
fit = 0;
for iter = 1 : maxiter
fitold = fit;
% update B
ete = (S' * S) .* (P' * P); % compute E'E
b = 2 * ete + u * eye(k);
c = 2 * mttkrp(X, {B, P, S}, 1) + u * P + U;
B = c / b;
% update P
ftf = (S' * S) .* (B' * B); % compute F'F
b = 2 * ftf + u * eye(k);
c = 2 * mttkrp(X, {B, P, S}, 2) + u * B - U;
P = c / b;
% update U
U = U + u * (P - B);
% update u
u = min(rho * u, umax);
% update S
tic;
[S, out] = OptStiefelGBB(...
S, #Sfun, opts, B, P, X, L, D, W, Y, alpha, beta);
tsolve = toc;
fprintf(...
['[S]: obj val %7.6e, cpu %f, #func eval %d, ', ...
'itr %d, |ST*S-I| %3.2e\n'], ...
out.fval, tsolve, out.nfe, out.itr, norm(S' * S - eye(k), 'fro'));
% update W
H = D * S;
W = (H' * H + gamma * eye(k)) \ H' * Y;
% compute the fit
T = ktensor({B, P, S});
normresidual = sqrt(normX ^ 2 + norm(T) ^ 2 - 2 * innerprod(X, T));
fit = 1 - (normresidual / normX);
fitchange = abs(fitold - fit);
if mod(iter, printitn) == 0
fprintf(' Iter %2d: fitdelta = %7.1e\n', iter, fitchange);
end
% check for convergence
if (iter > 1) && (fitchange < fitchangetol)
break;
end
end
%% clean up final results
T = arrange(T); % columns are normalized
fprintf('factorization error %3.2e\n', fit);
end
I know that there is little context here, but my suspicion is that I need to have Simulink, as Sfun is a Simulink related function(?). The script requires two toolboxes: tensor_toolbox, and FOptM.
Available at:
https://www.sandia.gov/~tgkolda/TensorToolbox/index-2.6.html
https://github.com/andland/FOptM
Thank you so much for your help,
Paul
Although SFun is an often used abbreviation for a Simulink S-Function, in this case the error has nothing to do with Simulink, and the name is a coincidence. (There is no Simulink related function specifically called Sfun, it is just a general term.)
Your error message has #Sfun in it, which is a way in MATLAB of creating a function handle to an (m-code) function called Sfun. I'd summize from the code you've shown that this is a cost function used in the optimization.
If you look at the code that your code is based on (tBNE_fun.m) you'll see that there is a function at the end of the file called Sfun. It is this that you are missing.
I am new to Matlab and trying to find a solution to the error of my code:
Not enough input arguments.
Error in F9>f (line 42)
y = (2 - 2*t*x) / (x^2 + 1) ;
Error in F9 (line 18)
e = euler(f, trange(1), y0_value, h, trange(end));
function [] = F9()
% Euler's Method to solve given functions
% Set initial values
hi = [1/2, 1/4];
trange = [0, 2];
y0_value = 1;
% Set functions' and exact functions' handles
% Calculate and show results
% Loop for functions
for i = 1:2
fprintf('###########\n');
fprintf('Function #%d\n', i)
fprintf('###########\n');
exact_value = f_exact(trange(end));
% Loop for h
for h = hi
% Euler calculations
e = euler(f, trange(1), y0_value, h, trange(end));
fprintf('\nh: %f\n', h);
fprintf('\nEuler: %f \n', e(end));
fprintf('Error: %f\n\n', abs((e(end)-exact_value)/exact_value));
end
fprintf('Exact: %f\n\n', exact_value);
end
end
% Euler's Method
function y = euler(f, t0, y0, h, tn)
n = (tn-t0)/h;
% Initialize t, y
[t, y] = deal(zeros(n, 1));
% Set t0, y0
t(1) = t0;
y(1) = y0;
for i = 1:n
t(i+1) = t(i) + h;
y(i+1) = y(i) + h/2 * (f(t(i), y(i))+ f(t(i+1) , y(i) + h * f(t(i), y(i))));
end
end
% Functions to solve
function y = f(t, x)
y = (2 - 2*t*x) / (x^2 + 1) ;
end
function y = f_exact(x)
y = (2*x + 1) / (x^2 + 1);
end
When you pass f to euler you need to pass it as a handle, i.e. precede it with a #:
e = euler(#f, trange(1), y0_value, h, trange(end));
I have an octave/Matlab function like this.
function [z] = baseline_als(y, lam, p, niter)
L = size(y);
D = sparse(diff(eye(L), 2));
w = ones(L);
for i = 1:niter
W = sparse.spdiags(w, 0, L, L); %error comes here
Z = W + lam * dot(D,transpose(D));
% z = spsolve(Z, w*y);
z= Z\(w*y);
w = p * (y > z) + (1-p) * (y < z);
end % End of For loop
end % End of function
I am calling this like this (in other file),
z = baseline_als(X,1000,0.00001,20)
plot(z)
Where X is 1D vector.
I have referred documentation from here. But could not figure out this error. How can I solve this?
i have to do an assignment where i have to find the depth of how much the ball is under water depending on the water's density, then i have to plot it. i don't have matlab at home but i'm using octave and for some reason it's not compiling, and it's not saying any errors. here is my code
function my_script()
% weight function
function func = weight(x,p)
func = p *pi* 4- 3 * pi*x ^2 + pi* x ^3;
% make the secant method
function root = secant(func , p, x0, x1, tol, count)
while count ~= 0
y1 = func(x0,p);
y2 = func(x1, p);
k = (x1 - x0)/(y2 - y1);
R = y2 * k;
root = x1 - R;
if abs(func(root,p)) < tol
break;
end
x0 = x1;
x1 = root;
count = count - 1;
end
%create array for depth values
y_val = [];
%input the roots into the array with a loop
for p = 0:0.01:1
t = secant(#weight, p, 0, 1, 0.000001, 1000000);
disp (t);
y_val = [y_val t];
end
% create the x - axis
x_val = 0 : 0.01 : 1;
%plotting the graph
figure;
plot (x_val, y_val)
xlabel('Density');
ylabel('Depth ');
title('Floating Sphere vs Density ');
Another way of creating what you have written is to split it into three different functions.
You'd have the weight function, weight.m,
% weight function
function func = weight(x,p)
func = p *pi* 4- 3 * pi*x ^2 + pi* x ^3;
and the secant method function, secant.m,
% make the secant method
function root = secant(func , p, x0, x1, tol, count)
while count ~= 0
y1 = func(x0,p);
y2 = func(x1, p);
k = (x1 - x0)/(y2 - y1);
R = y2 * k;
root = x1 - R;
if abs(func(root,p)) < tol
break;
end
x0 = x1;
x1 = root;
count = count - 1;
end
%create array for depth values
y_val = [];
%input the roots into the array with a loop
for p = 0:0.01:1
t = secant(#weight, p, 0, 1, 0.000001, 1000000);
disp (t);
y_val = [y_val t];
end
% create the x - axis
x_val = 0 : 0.01 : 1;
%plotting the graph
figure;
plot (x_val, y_val)
xlabel('Density');
ylabel('Depth ');
title('Floating Sphere vs Density ');
Then you'd have my_script():
function my_script()
but it is an empty function, so the output is correct! You have to have all the commands for each function finished before you define the next function.
I have a feeling that you want to take out everything from the end of the while loop onwards from the secant function and put it into the main my_script() function.
Here's your code, Octave style. Observe that I temporarily commented the "disp(t);" statement to avoid a long listing of values. This way, the plot is plotted immediately. Hopefully this helps.
function my_script
%create array for depth values
y_val = [];
%input the roots into the array with a loop
for p = 0:0.01:1
t = secant(#weight, p, 0, 1, 0.000001, 1000000);
%disp (t);
y_val = [y_val t];
endfor
% create the x - axis
x_val = 0 : 0.01 : 1;
%plotting the graph
figure(1)
plot (x_val, y_val)
xlabel('Density');
ylabel('Depth ');
title('Floating Sphere vs Density ');
endfunction
% make the secant method
function root = secant(func , p, x0, x1, tol, count)
while count ~= 0
y1 = func(x0,p);
y2 = func(x1, p);
k = (x1 - x0)/(y2 - y1);
R = y2 * k;
root = x1 - R;
if abs(func(root,p)) < tol
break;
end
x0 = x1;
x1 = root;
count = count - 1;
endwhile
endfunction
% weight function
function func = weight(x,p)
func = p *pi* 4- 3 * pi*x ^2 + pi* x ^3;
endfunction