Matlab, Cannot get fgoalattain to work to save my life - matlab

I cannot get fgoalattain to work to save my life. It just comes with the following errors that I have not figured out how to fix despite several hours of messing with the highlighted areas. The issues with interpolation work fine until I use fgolattain and the fgoalattain is used as specified in documentation.
Help?
Error using griddedInterpolant The number of input coordinate arrays
does not equal the number of dimensions (NDIMS) of these arrays.
Error in Scan (line 5) F = griddedInterpolant(xx',yy',a','cubic'); %
Prepare image for interpolation
Error in #(vals)Scan(vals,xx,yy,nr,m,d)
Error in goalcon (line 63)
f = feval(funfcn{3},x,varargin{:});
Error in fgoalattain (line 399)
[ctmp,ceqtmp] = feval(cfun{3},xnew,extravarargin{:});
Error in Cu (line 24) xz =
fgoalattain(#(vals)Scan(vals,xx,yy,nr,m,d),x0,goal,weight);
clear all;
close all;
clc
% Create ring
x = -31:31;
[xx,yy] = meshgrid(x,x); % 2-D arrays with x and y-coord. respectively
r = sqrt(xx.^2+yy.^2)/31; % Distance to center of grid
a = 2*exp(max(-40.0,-6000.0*(r-0.7).^4)).*(1.1-0.75*yy/31.0);
a = a/max(max(a)); % Normalize a so in range [0,1]
% Create the scan. This time specify size as desired
nr = 60; % Number of rays for each angle
m = 66; % Number of angles to use
%scan function
sc = Scan(a,xx,yy,nr,m);
%applying optimization tool
x0 = rand();
goal = sc;
weight = abs(sc);
xz = fgoalattain(#(vals)Scan(vals,xx,yy,nr,m),x0,goal,weight);
figure
mesh(xz)
drawnow
figure
pcolor(xz)
drawnow
with Scan function written as:
function [ sc ] = Scan( a, xx, yy, nr, m)
d = zeros(nr,m); % Array to hold the scan vectors
xt = linspace(-31,31,nr);
[xx1,yy1] = meshgrid(xt,xt);
F = griddedInterpolant(xx',yy',a','cubic'); % Prepare image for interpolation
for j=0:m-1 % Loop over m angles
th = pi*j/m; st = sin(th); ct = cos(th);
xr = xx1*ct-yy1*st; % Generate the x1,x2-coordinates for
yr = xx1*st+yy1*ct; % the grid points in the xp1,xp2 grid.
s = F(xr',yr')'; % Interpolate
d(:,j+1) = sum(s,2); % Sum along each ray
end
sc = d/max(max(d)); % Normalize so max value = 1.
end

Related

Incorrect dimensions for matrix multiplication

I just want to make some predictions using these calculations but I'm getting this error: Error using * Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication.
Error in main (line 64) r=(pn')*(best);
the dataset
Main driver
clear; clc;
%load dataset
ds = load('ex1data1.txt');
%split x/y
x = ds(:,1); % Examples
y = ds(:,2);
n=1;
m=length(y);
format long;
b1 = x\y; %intercept
%plot lineer regression
% Top plot
yCalc1 = b1*x;
ax1 = nexttile;
scatter(ax1,x,y,'o');
hold on
plot(ax1,x,yCalc1);
title(ax1,'Linear Regression Relation Between Profit & Truck')
ax1.FontSize = 14;
ax1.XColor = 'red';
ylabel('profit of a food truck');
xlabel('population of a city');
grid on
%normalise
[x,maxs,mins]=normalize(x);
%add column with ones - help hyphothesizs
xo=[ones(m,1),x];
%gradient descent
repeat=1500;
lrate=0.01;
thetas=zeros(2,1);
[best,costs] = gradientDescent(repeat,lrate,thetas,xo,y,m);
% plot 𝑱(𝜽) vs iteration
ax2 = nexttile;
scatter(ax2,costs,1:repeat)
title(ax2,' 𝑱(𝜽) vs iteration')
grid(ax2,'on')
ylabel('Iteration');
xlabel('J(𝜽)');
%prediction
p=[7;7];
pn=(p-maxs')./(maxs'-mins');
pn = [1;pn];
r=(pn')*(best);
Gradient Descent
function [thetas,costs] = gradientDescent(repeat,lrate,thetas,xo,y,m)
costs = zeros(repeat,1);
for r = 1:repeat
hc=xo*thetas - y;
tempintercept=sum(hc.*xo);
thetas = thetas - (lrate * (1/m)) * tempintercept';
costs(r)=cost(thetas,xo,y);
end
end
Normalize
function [x,maxs,mins] = normalize (x)
x=(x-max(x))./(max(x)/min(x));
maxs=max(x);
mins=min(x);
end

Downloaded Non-local means filter does not work

Below is a downloaded (I have customized it a little bit) algorithm for the Non-local means filter:
function [cleared] = Non_Local_Means(I,f,t,h)
[m,n] = size(I);
% Making gaussian kernel
su=1; %standard deviation of gaussian kernel
sm=0; % sum of all kernel elements (for normalization)
ks= 2*f+1; % size of kernel (same as neighborhood window size)
% Initiating kernel
ker = zeros(ks,ks);
for x=1:ks
for y=1:ks
ab = x-f-1; %horizontal distance of pixel from center(f+1, f+1)
cd = y-f-1; % vertical distance of pixel from center (f+1, f+1)
ker(x,y) = 100*exp(((ab*ab)+(cd*cd))/(-2*(su*su)));
sm = sm + ker(x,y);
end
end
kernel = ker ./ f;
kernel = kernel / sm; % normalization
% Assign a clear output image
cleared = zeros(m,n);
I = padarray(I,[f,f],'symmetric');
% Now we'll calculate ouput for each pixel
for i=1:m
for j=1:n
im = i+f; % to compensate for shift due to padarray function
jn= j+f;
% neighborhood of concerned pixel (we called it similarity window)
W1 = I(im-f:im+f , jn-f:jn+f);
% BOundaries of similarity window for that pixel
rmin = max(im-t, f+1);
rmax = min(im+t, m+f);
smin = max(jn-t, f+1);
smax = min(jn+t, n+f);
% Calculate weighted average next
NL=0; % same as cleared (i,j) but for simplicity
Z =0; % sum of all s(i,j)
% Run loop through all the pixels in similarity window
for r=rmin:rmax
for s=smin:smax
% neighborhood of pixel 'j' being compared for similarity
W2 = I(r-f:r+f, s-f:s+f);
% square of weighted euclidian distances
d2 = sum(sum(kernel.*(W1-W2).*(W1-W2))); %LINE 67
% weight of similarity between both pixels : s(i,j)
sij = exp(-d2/(h*h));
% update Z and NL
Z = Z + sij;
NL = NL + (sij*I(r,s));
end
end
% normalization of NL
cleared(i,j) = NL/Z;
end
end
% convert cleared to uint8
cleared = uint8(cleared);
end
But it gives me a subsequent mistake:
Error using .*
Integers can only be combined with integers of the same class, or scalar doubles.
Error in Non_Local_Means (line 67)
d2 = sum(sum(kernel.(W1-W2).(W1-W2)));
Error in filter_process (line 32)
eval(['filter_Images.',name_of_cells{i},'(',num2str(m),')','.',column_name{n},'(:,:,',num2str(p),')=Non_Local_Means(filter_Images.',name_of_cells{i},'(',num2str(m),')','.',column_name{n},'(:,:,',num2str(p),'),f,t,h);'])
Error in untitled>pushbutton13_Callback (line 1157)
handles.filtered_Images = filter_process(Images, f, t, h);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in untitled (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in #(hObject,eventdata)untitled('pushbutton13_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callback
How can I solve this problem (LINE 67)?
Thank you in advance!

MATLAB's lsim() vs for-loop Simulation // Different results for the same system

I've spent quite some time trying to simulate a simple SISO system using two approaches:
1) Using lsim() in MATLAB
2) By writing down the difference equations myself and iterate over them in a loop.
I was never able to get the same simulation results from both approaches, and I have no idea what I am doing wrong.
I stacked my code in a single m-file so it's easier to follow. Here is the code:
function main()
clear all
clc
simulateUsing_lsim()
simulateUsing_loop()
end
%%%%%% Simulating using lsim %%%%%%%
function simulateUsing_lsim()
% Define the continuous-time closed-loop system
P = getContPlant();
[Kp,Ki,Kd] = get_PIDgains();
C = pid(Kp,Ki,Kd);
clSys_cont = feedback(C*P,1);
% Define the discrete-time closed-loop system
hk = get_sampling_time();
clSys_disc = c2d(clSys_cont,hk);
% Generate the reference signal and the time vector
[r,t] = getReference(hk);
%% Simulate and plot using lsim
figure
lsim(clSys_disc,r,t)
%% Finding and plotting the error
y = lsim(clSys_disc,r);
e = r - y;
figure
p = plot(t,e,'b--');
set(p,'linewidth',2)
legend('error')
xlabel('Time (seconds)')
ylabel('error')
% xlim([-.1 10.1])
end
%%%%%% Simulating using loop iteration (difference equations) %%%%%%%
function simulateUsing_loop()
% Get the cont-time ol-sys
P = getContPlant();
% Get the sampling time
hk = get_sampling_time();
% Get the disc-time ol-sys in SS representation
P_disc = ss(c2d(P,hk));
Ad = P_disc.A;
Bd = P_disc.B;
Cd = P_disc.C;
% Get the PID gains
[Kp,Ki,Kd] = get_PIDgains();
% Generate the reference signal and the time vector
[r,t] = getReference(hk);
%% Perform the system simulation
x = [0 0]'; % Set initial states
e = 0; % Set initial errors
integral_sum = 0; % Set initial integral part value
for i=2:1:length(t)
% Calculate the output signal "y"
y(:,i) = Cd*x;
% Calculate the error "e"
e(:,i) = y(:,i) - r(i);
% Calculate the control signal vector "u"
integral_sum = integral_sum + Ki*hk*e(i);
u(:,i) = Kp*e(i) + integral_sum + (1/hk)*Kd*(e(:,i)-e(:,i-1));
% Saturation. Limit the value of u withing the range [-tol tol]
% tol = 100;
% if abs(u(:,i)) > tol
% u(:,i) = tol * abs(u(:,i))/u(:,i);
% else
% end
% Calculate the state vector "x"
x = Ad*x + Bd*u(:,i); % State transitions to time n
end
%% Subplots
figure
plot(t,y,'b',t,r,'g--')
%% Plotting the error
figure
p = plot(t,e,'r');
set(p,'linewidth',2)
legend('error')
xlabel('Time (seconds)')
ylabel('error')
end
function P = getContPlant()
s = tf('s');
P = 1/(s^2 + 10*s + 20);
end
function [Kp,Ki,Kd] = get_PIDgains()
Kp = 350;
Ki = 300;
Kd = 50;
end
function hk = get_sampling_time()
hk = 0.01;
end
function [r,t] = getReference(hk)
[r,t] = gensig('square',4,10,hk);
end
I got the plant model P and its PID controller from this page (see equation 10), where the system is simulated against a step reference and the result looks pretty much exactly like the lsim() result (just for a single step peak).
However, the result of simulating the system using lsim() is this:
whereas, using the for loop, I got this performance:
I would highly appreciate any help or clarification why I am getting different results.

Two plots of same wave in MatLab, but plot created after transforming to polar coordinates is distorded?

I have created some MatLab code that plots a plane wave using two different expressions that give the same plane wave. The first expression is in Cartesian coordinates and works fine. However, the second expression is in polar coordinates and when I calculate the plane wave in this case, the plot is distorted. Both plots should look the same. So what am I doing wrong in transforming to/from polar coordinates?
function Plot_Plane_wave()
clc
clear all
close all
%% Step 0. Input paramaters and derived parameters.
alpha = 0*pi/4; % angle of incidence
k = 1; % wavenumber
wavelength = 2*pi/k; % wavelength
%% Step 1. Define various equivalent versions of the incident wave.
f_u_inc_1 = #(alpha,x,y) exp(1i*k*(x*cos(alpha)+y*sin(alpha)));
f_u_inc_2 = #(alpha,r,theta) exp(1i*k*r*cos(theta-alpha));
%% Step 2. Evaluate the incident wave on a grid.
% Grid for field
gridMax = 10;
gridN = 2^3;
g1 = linspace(-gridMax, gridMax, gridN);
g2 = g1;
[x,y] = meshgrid(g1, g2);
[theta,r] = cart2pol(x,y);
u_inc_1 = f_u_inc_1(alpha,x,y);
u_inc_2 = 0*x;
for ir=1:gridN
rVal = r(ir);
for itheta=1:gridN
thetaVal = theta(itheta);
u_inc_2(ir,itheta) = f_u_inc_2(alpha,rVal,thetaVal);
end
end
%% Step 3. Plot the incident wave.
figure(1);
subplot(2,2,1)
imagesc(g1(1,:), g1(1,:), real(u_inc_1));
hGCA = gca; set(hGCA, 'YDir', 'normal');
subplot(2,2,2)
imagesc(g1(1,:), g1(1,:), real(u_inc_2));
hGCA = gca; set(hGCA, 'YDir', 'normal');
end
Your mistake is that your loop is only going through the first gridN values of r and theta. Instead you want to step through the indices of ix and iy and pull out the rVal and thetaVal of the matrices r and theta.
You can change your loop to
for ix=1:gridN
for iy=1:gridN
rVal = r(ix,iy); % Was equivalent to r(ix) outside inner loop
thetaVal = theta(ix,iy); % Was equivalent to theta(iy)
u_inc_2(ix,iy) = f_u_inc_2(alpha,rVal,thetaVal);
end
end
which gives the expected graphs.
Alternatively you can simplify your code by feeding matrices in to your inline functions. To do this you would have to use an elementwise product .* instead of a matrix multiplication * in f_u_inc_2:
alpha = 0*pi/4;
k = 1;
wavelength = 2*pi/k;
f_1 = #(alpha,x,y) exp(1i*k*(x*cos(alpha)+y*sin(alpha)));
f_2 = #(alpha,r,theta) exp(1i*k*r.*cos(theta-alpha));
% Change v
f_old = #(alpha,r,theta) exp(1i*k*r *cos(theta-alpha));
gridMax = 10;
gridN = 2^3;
[x,y] = meshgrid(linspace(-gridMax, gridMax, gridN));
[theta,r] = cart2pol(x,y);
subplot(1,3,1)
contourf(x,y,real(f_1(alpha,x,y)));
title 'Cartesian'
subplot(1,3,2)
contourf(x,y,real(f_2(alpha,r,theta)));
title 'Polar'
subplot(1,3,3)
contourf(x,y,real(f_old(alpha,r,theta)));
title 'Wrong'

Gaussian Process Regression

I am coding a Gaussian Process regression algorithm. Here is the code:
% Data generating function
fh = #(x)(2*cos(2*pi*x/10).*x);
% range
x = -5:0.01:5;
N = length(x);
% Sampled data points from the generating function
M = 50;
selection = boolean(zeros(N,1));
j = randsample(N, M);
% mark them
selection(j) = 1;
Xa = x(j);
% compute the function and extract mean
f = fh(Xa) - mean(fh(Xa));
sigma2 = 1;
% computing the interpolation using all x's
% It is expected that for points used to build the GP cov. matrix, the
% uncertainty is reduced...
K = squareform(pdist(x'));
K = exp(-(0.5*K.^2)/sigma2);
% upper left corner of K
Kaa = K(selection,selection);
% lower right corner of K
Kbb = K(~selection,~selection);
% upper right corner of K
Kab = K(selection,~selection);
% mean of posterior
m = Kab'*inv(Kaa+0.001*eye(M))*f';
% cov. matrix of posterior
D = Kbb - Kab'*inv(Kaa + 0.001*eye(M))*Kab;
% sampling M functions from from GP
[A,B,C] = svd(Kaa);
F0 = A*sqrt(B)*randn(M,M);
% mean from GP using sampled points
F0m = mean(F0,2);
F0d = std(F0,0,2);
%%
% put together data and estimation
F = zeros(N,1);
S = zeros(N,1);
F(selection) = f' + F0m;
S(selection) = F0d;
% sampling M function from posterior
[A,B,C] = svd(D);
a = A*sqrt(B)*randn(N-M,M);
% mean from posterior GPs
Fm = m + mean(a,2);
Fmd = std(a,0,2);
F(~selection) = Fm;
S(~selection) = Fmd;
%%
figure;
% show what we got...
plot(x, F, ':r', x, F-2*S, ':b', x, F+2*S, ':b'), grid on;
hold on;
% show points we got
plot(Xa, f, 'Ok');
% show the whole curve
plot(x, fh(x)-mean(fh(x)), 'k');
grid on;
I expect to get some nice figure where the uncertainty of unknown data points would be big and around sampled data points small. I got an odd figure and even odder is that the uncertainty around sampled data points is bigger than on the rest. Can someone explain to me what I am doing wrong? Thanks!!
There are a few things wrong with your code. Here are the most important points:
The major mistake that makes everything go wrong is the indexing of f. You are defining Xa = x(j), but you should actually do Xa = x(selection), so that the indexing is consistent with the indexing you use on the kernel matrix K.
Subtracting the sample mean f = fh(Xa) - mean(fh(Xa)) does not serve any purpose, and makes the circles in your plot be off from the actual function. (If you choose to subtract something, it should be a fixed number or function, and not depend on the randomly sampled observations.)
You should compute the posterior mean and variance directly from m and D; no need to sample from the posterior and then obtain sample estimates for those.
Here is a modified version of the script with the above points fixed.
%% Init
% Data generating function
fh = #(x)(2*cos(2*pi*x/10).*x);
% range
x = -5:0.01:5;
N = length(x);
% Sampled data points from the generating function
M = 5;
selection = boolean(zeros(N,1));
j = randsample(N, M);
% mark them
selection(j) = 1;
Xa = x(selection);
%% GP computations
% compute the function and extract mean
f = fh(Xa);
sigma2 = 2;
sigma_noise = 0.01;
var_kernel = 10;
% computing the interpolation using all x's
% It is expected that for points used to build the GP cov. matrix, the
% uncertainty is reduced...
K = squareform(pdist(x'));
K = var_kernel*exp(-(0.5*K.^2)/sigma2);
% upper left corner of K
Kaa = K(selection,selection);
% lower right corner of K
Kbb = K(~selection,~selection);
% upper right corner of K
Kab = K(selection,~selection);
% mean of posterior
m = Kab'/(Kaa + sigma_noise*eye(M))*f';
% cov. matrix of posterior
D = Kbb - Kab'/(Kaa + sigma_noise*eye(M))*Kab;
%% Plot
figure;
grid on;
hold on;
% GP estimates
plot(x(~selection), m);
plot(x(~selection), m + 2*sqrt(diag(D)), 'g-');
plot(x(~selection), m - 2*sqrt(diag(D)), 'g-');
% Observations
plot(Xa, f, 'Ok');
% True function
plot(x, fh(x), 'k');
A resulting plot from this with 5 randomly chosen observations, where the true function is shown in black, the posterior mean in blue, and confidence intervals in green.