Matrix dimensions error when using norm() - matlab

I'm trying to use MATLAB to run Richardson's iteration for computing the solution of a linear system, Ax=b. I wrote a function to do this, but got an error when I tried to run it. The following is my function where x0 is the initial iterate, L is the maximum number of iterations, A is a nonsingular nxn matrix, b is a n-length vector, a is in place of the alpha parameter required for the algorithm, tol is the desired level of precision, x is a n-length vector, and k is the actual number of iterations:
function [x,k]=Richardson(x0,L,A,b,a,tol)
n = size(b);
x1 = x0 + a*(b-A*x0);
Norm = norm(x1-x0)/sqrt(n);
k = 1;
x0 = x1;
while (Norm > tol) && (k < L)
x1 = x0 + a*(b-A*x0);
Norm = norm(x1-x0)/sqrt(n);
k = k + 1;
x0 = x1;
end
x = x1;
I tried to run this function using the following:
x0=[0;0;0];
L = 10;
A=[1,0,0;0,2,0;0,0,4];
b=[1;1;1];
a=-1;
tol=10.^(-5);
a1=Richardson(x0,L,A,b,a,tol)
This was the error I got:
Error using /
Matrix dimensions must agree.
Error in Richardson (line 4)
Norm = norm(x1-x0)/sqrt(n);
Error in HW8 (line 11)
a1=Richardson(x0,L,A,b,a,tol)
I don't see how this is the case, because x0 and x1 are both n-length vectors. Am I implementing this incorrectly?

n = size(b);
Results in a 2 values vector (3,1 in your case). So you can't divide a single value by 2 values. Change to
n = size(b,1) or n=size(b,2) to get what you need (rows or columns).

Related

Why matlab gives fminsearch optimisation error?

I have such an question, And I will do it in matlab. But, I get some errors:
Find the value of x ∈ [0, 1] that minimizes the largest eigenvalue of the matrix A(x) = xM +(1−x)P, where M is a 5×5 magic square and P is a 5 × 5 Pascal matrix.
My matlab code:
%Define Matrices
M = magic(5);
P = pascal (5);
% Define the variable x
syms x
%Define the given matrix A
>> A = x*M + (1-x)*P;
%Define the eigenvalue lambda as y;
syms y
%Find determinant of |A - lambda * I|
D = det (A - y*eye(5))
%Define Objective function
objective = #(y) y
%And Define the constraint
constraint = #(x,y) (-1)*D
%initial value x0 = (0:0.001:1);
%Minimization problem solving
x = fmincon(objective, constraint, x0)
I get this error;
Error using fmincon (line 221)
FMINCON requires the following inputs to be of data type double: 'X0'.
Or If I use another function: fminsearch
x = fminsearch(objective, constraint, x0)
In this case I get the following error:
Error using fminsearch (line 96)
FMINSEARCH accepts inputs only of data type double.
How can I deal with these errors ? Where is my mistake? How can I correct them?
I guess what you are looking for might be fminbnd, which helps to
Find minimum of single-variable function on fixed interval
n = 5;
M = magic(n);
P = pascal(n);
x = fminbnd(#(x) max(eig(x*M + (1-x)*P)),0,1);
such that
>> x
x = 0.79603
I suspect you did not show us the proper code, as you have sums there. I suspect you mean syms.
fmincon only works for numeric data, not symbolic data.

how to randomly multiply symbolic array with matrix

Assuming a matrix W of dimensions n-by-n which is known, and its elements are positive numbers between 0 and 1.
Assuming also a symbolic vector
k = [a b c d];
I need to randomly multiply each all the non-zero component of W with one at a time of the components of k(randomly), such as e.g.:
What I tried:
k = sym('a', [1 4]);
msize = numel(k);
k(randperm(msize, 1))
for i = 1:length(W)
for j = 1:length(W)
W(i,j) = W(i,j)*(k);
end
end
and the error was the following:
The following error occurred converting from sym to double:
Error using maplemex
Error, (in MTM:-double) cannot handle unevaluated name `a1` in evalhf
First we define the inputs:
% PARAMETERS
% k: symbolic vector of length m
m = 4;
k = sym('a', [1, m]);
% W: n-by-n matrix of doubles
n = 5;
W = rand(n);
Here is the calculation:
% CALCULATION
% random assignment of elements of k to the shape of W
I = randi(m, n);
K = k(I);
% result: element-wise multiplication of K and W
result = K .* W;

Vectorize with Matlab Meshgrid in Chebfun

I am trying to use meshgrid in Matlab together with Chebfun to get rid of double for loops. I first define a quasi-matrix of N functions,
%Define functions of type Chebfun
N = 10; %number of functions
x = chebfun('x', [0 8]); %Domain
psi = [];
for i = 1:N
psi = [psi sin(i.*pi.*x./8)];
end
A sample calculation would be to compute the double sum $\sum_{i,j=1}^10 psi(:,i).*psi(:,j)$. I can achieve this using two for loops in Matlab,
h = 0;
for i = 1:N
for j = 1:N
h = h + psi(:,i).*psi(:,j);
end
end
I then tried to use meshgrid to vectorize in the following way:
[i j] = meshgrid(1:N,1:N);
h = psi(:,i).*psi(:,j);
I get the error "Column index must be a vector of integers". How can I overcome this issue so that I can get rid of my double for loops and make my code a bit more efficient?
BTW, Chebfun is not part of native MATLAB and you have to download it in order to run your code: http://www.chebfun.org/. However, that shouldn't affect how I answer your question.
Basically, psi is a N column matrix and it is your desire to add up products of all combinations of pairs of columns in psi. You have the right idea with meshgrid, but what you should do instead is unroll the 2D matrix of coordinates for both i and j so that they're single vectors. You'd then use this and create two N^2 column matrices that is in such a way where each column corresponds to that exact column numbers specified from i and j sampled from psi. You'd then do an element-wise multiplication between these two matrices and sum across all of the columns for each row. BTW, I'm going to use ii and jj as variables from the output of meshgrid instead of i and j. Those variables are reserved for the complex number in MATLAB and I don't want to overshadow those unintentionally.
Something like this:
%// Your code
N = 10; %number of functions
x = chebfun('x', [0 8]); %Domain
psi = [];
for i = 1:N
psi = [psi sin(i.*pi.*x./8)];
end
%// New code
[ii,jj] = meshgrid(1:N, 1:N);
%// Create two matrices and sum
matrixA = psi(:, ii(:));
matrixB = psi(:, jj(:));
h = sum(matrixA.*matrixB, 2);
If you want to do away with the temporary variables, you can do it in one statement after calling meshgrid:
h = sum(psi(:, ii(:)).*psi(:, jj(:)), 2);
I don't have Chebfun installed, but we can verify that this calculates what we need with a simple example:
rng(123);
N = 10;
psi = randi(20, N, N);
Running this code with the above more efficient solution gives us:
>> h
h =
8100
17161
10816
12100
14641
9216
10000
8649
9025
11664
Also, running the above double for loop code also gives us:
>> h
h =
8100
17161
10816
12100
14641
9216
10000
8649
9025
11664
If you want to be absolutely sure, we can have both codes run with the outputs as separate variables, then check if they're equal:
%// Setup
rng(123);
N = 10;
psi = randi(20, N, N);
%// Old code
h = 0;
for i = 1:N
for j = 1:N
h = h + psi(:,i).*psi(:,j);
end
end
%// New code
[ii,jj] = meshgrid(1:N, 1:N);
hnew = sum(psi(:, ii(:)).*psi(:, jj(:)), 2);
%// Check for equality
eql = isequal(h, hnew);
eql checks if both variables are equal, and we do get them as such:
>> eql
eql =
1

USE DIFFERENTIAL MATRIX OPERATOR TO SOLVE ODE

We were asked to define our own differential operators on MATLAB, and I did it following a series of steps, and then we should use the differential operators to solve a boundary value problem:
-y'' + 2y' - y = x, y(0) = y(1) =0
my code was as follows, it was used to compute this (first and second derivative)
h = 2;
x = 2:h:50;
y = x.^2 ;
n=length(x);
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
% the code above creates the upper and lower shift matrix
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2); %second differential operator
d1= D*y.'
d2= ((D2)*y.')
then I changed it to this after posting it here and getting one response that encouraged the usage of Identity Matrix, however I still seem to be getting no where.
h = 2;
n=10;
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2); %second differential operator
I= eye(n);
eqn=(-D2 + 2*D - I)*y == x
solve(eqn,y)
I am not sure how to proceed with this, like should I define y and x, or what exactly? I am clueless!
Because this is a numerical approximation to the solution of the ODE, you are seeking to find a numerical vector that is representative of the solution to this ODE from time x=0 to x=1. This means that your boundary conditions make it so that the solution is only valid between 0 and 1.
Also this is now the reverse problem. In the previous post we did together, you know what the input vector was, and doing a matrix-vector multiplication produced the output derivative operation on that input vector. Now, you are given the output of the derivative and you are now seeking what the original input was. This now involves solving a linear system of equations.
Essentially, your problem is now this:
YX = F
Y are the coefficients from the matrix derivative operators that you derived, which is a n x n matrix, X would be the solution to the ODE, which is a n x 1 vector and F would be the function you are associating the ODE with, also a n x 1 vector. In our case, that would be x. To find Y, you've pretty much done that already in your code. You simply take each matrix operator (first and second derivative) and you add them together with the proper signs and scales to respect the left-hand side of the ODE. BTW, your first derivative and second derivative matrices are correct. What's left is adding the -y term to the mix, and that is accomplished by -eye(n) as you have found out in your code.
Once you formulate your Y and F, you can use the mldivide or \ operator and solve for X and get the solution to this linear system via:
X = Y \ F;
The above essentially solves the linear system of equations formed by Y and F and will be stored in X.
The first thing you need to do is define a vector of points going from x=0 to x=1. linspace is probably the most suitable where you can specify how many points we want. Let's assume 100 points for now:
x = linspace(0,1,100);
Therefore, h in our case is just 1/100. In general, if you want to solve from the starting point x = a up to the end point x = b, the step size h is defined as h = (b - a)/n where n is the total number of points you want to solve for in the ODE.
Now, we have to include the boundary conditions. This simply means that we know the beginning and ending of the solution of the ODE. This means that y(0) = y(1) = 0. As such, we make sure that the first row of Y has only the first column set to 1 and the last row of Y has only the last column set to 1, and we'll set the output position in F to both be 0. This symbolizes that we already know the solution at these points.
Therefore, your final code to solve is just:
%// Setup
a = 0; b = 1; n = 100;
x = linspace(a,b,n);
h = (b-a)/n;
%// Your code
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2);
%// New code - Create differential equation matrix
Y = (-D2 + 2*D - eye(n));
%// Set boundary conditions on system
Y(1,:) = 0; Y(1,1) = 1;
Y(end,:) = 0; Y(end,end) = 1;
%// New code - Create F vector and set boundary conditions
F = x.';
F(1) = 0; F(end) = 0;
%// Solve system
X = Y \ F;
X should now contain your numerical approximation to the ODE in steps of h = 1/100 starting from x=0 up to x=1.
Now let's see what this looks like:
figure;
plot(x, X);
title('Solution to ODE');
xlabel('x'); ylabel('y');
You can see that y(0) = y(1) = 0 as per the boundary conditions.
Hope this helps, and good luck!

How to use summation in MATLAB?

I have a randomly generated vector, say A of length M.
Say:
A = rand(M,1)
And I also have a function, X(k) = sin(2*pi*k).
How would I find Y(k) which is summation of A(l)*X(k-l) as l goes from 0 to M?
Assume any value of k... But the answer should be summation of all M+1 terms.
Given M and k, this is how you can perform your summation:
A = rand(M+1,1); %# Create M+1 random values
Y = sin(2*pi*(k-(0:M)))*A; %# Use a matrix multiply to perform the summation
EDIT: You could even create a function for Y that takes k and A as arguments:
Y = #(k,A) sin(2*pi*(k+1-(1:numel(A))))*A; %# An anonymous function
result = Y(k,A); %# Call the function Y
A = rand(1, M + 1);
X = sin(2 * pi * (k - (0 : M)));
total = sum(A .* X);
You may be looking for the convolution of the vectors A and X:
Y = conv(A, X);
If you're trying to do a fourier transform, you should also look at fft.