0
votes

I am getting the error "inner matrix dimensions must agree" in the code below

t = linspace(0,10,100);
x_exact = exp(-(t-4).^2); % exact solution
x_exact = x_exact';
lambda = randn(size(x_exact)); % diagonal values

A = diag(lambda); % diagonal matrix
y = A*x_exact; % exact data
delta = 1e-3*randn(size(y)); % noise
y_delta = y+delta; % noisy data

%% Define functional

% preallocate the memory
N_alpha = 3;
alpha = zeros(1,N_alpha);
resulting_x = cell(1,N_alpha);

alpha(1) = 1e-9;
alpha(N_alpha) = 1;

x = zeros(100,1);

for n = 1:N_alpha
    alpha(n) = alpha(1)+(n-1)*((alpha(N_alpha)-alpha(1))/(N_alpha-1));
    alphas = alpha(n);
    T = @(x) 1/2*norm(A*x-y_delta)^2+(alphas/2)*norm(x)^2; 
    resulting_x{n} = fminsearch(@(x) T(x),zeros(1,N_alpha));
end

specifically on the line T = @(x) 1/2*norm(A*x-y_delta)^2+(alphas/2)*norm(x)^2;. I have tried to change * to the pointwise product .* but then I get the error "inner matrix dimensions must agree".

x is supposed to be vector input which will be well defined when multiplied by the matrix A, but this function handle is causing some problems

2

2 Answers

1
votes

You have to consider what are you trying to minimise T with respect to. The initial conditions x0 which you supply (in your case zeros(1,N_alpha) should be usable in place of x when your function is T. They are not, as x should be a 100-element column vector, not a 3 element row vector!

Using this will work:

resulting_x{n} = fminsearch(@(x) T(x),zeros(100,1));

But it seems perhaps you're confused about what x is, because you don't need to define it above the loop. Perhaps you meant to do

x0 = zeros(100,1);
for n = 1:N_alpha
    alpha(n) = alpha(1)+(n-1)*((alpha(N_alpha)-alpha(1))/(N_alpha-1));
    alphas = alpha(n);
    T = @(x) 1/2*norm(A*x-y_delta)^2+(alphas/2)*norm(x)^2; 
    resulting_x{n} = fminsearch(@(x) T(x), x0);
end

For more information, see the fminsearch documentation

0
votes

Your function

@(x) 1/2*norm(A*x-y_delta)^2+(alphas/2)*norm(x)^2

tries to multiply matrix A by its input argument x. But your code sets up A as a 100 x 100 matrix, while the call to fminsearch tells it that the initial input to the function should be a 1 x 3 vector. That's why you correctly get the Inner matrix dimensions must agree error.

Your code is making one out of A and x the wrong size; you need to compare what the code is doing against the algorithm you're trying to implement to determine which.