Inner matrix dimensions must agree? - matlab

this is my first matlab script, so this question may seem basic and blindingly obvious, but I am a little stuck at the moment.
I have a matlab script of two lines:
x = linspace(0,4*pi,100);
y = exp(-x) * sin(x);
I'm going off the Create 2-D Line Graph tutorial on Mathworks. I want to plot f(x) = e^(-x)sin(x) over the range 0 to 4pi, but I get an inner matrix dimensions must agree error on the second line. I'm not sure what's going on, because I don't think I'm creating any matrices at the moment. Any help would be appreciated! Is there something simple with syntax that I am missing? Thanks!

This is a very simple error to resolve, and I'll admit that it's a common error that most MATLAB programmers face when facing MATLAB for the first time. Specifically, when you do this line:
y = exp(-x) * sin(x);
This operation is assuming that you will perform a matrix multiplication. What you actually want to do is an element-by-element operation. You want the points in exp(-x) to multiply with the corresponding elements in sin(x). #ellieadam provided some nice links for you to review what these operations are, but if you want to do element-by-element operations, you need to add a dot (.) before the multiplication operator. As such, you need to do this instead:
y = exp(-x) .* sin(x); %// Note the dot!
This line should now work.
As a bonus for you, here's a simple example. Suppose I have these two matrices:
A = [1 2;
3 4];
B = [4 3;
2 1];
By doing A * B in MATLAB, you get:
>> A * B
ans =
8 5
20 13
Note that this will perform a matrix multiplication. By doing A .* B, this is what I get:
>> A .* B
ans =
4 6
6 4
What's different with this statement is that one element in A is multiplied by the corresponding element in B. The first row and first column of A gets multiplied by the first row, first column of B, and the same location in the output matrix is where this result is stored. You can follow along with the other elements in the output matrix and it'll give you the same behaviour. There are other element-by-element operations, such as division and exponentiation. Addition and subtraction are inherently element-by-element, as performing these operations on matrices is by definition in this fashion.
To add to #ellieadam's post, check this MathWorks post out that specifically shows you the various operations on matrices and vectors, including element-by-element operations:
http://www.mathworks.com/help/matlab/matlab_prog/array-vs-matrix-operations.html

Based on your code, your x variable is a vector. Therefore, when you are multiplying the term exp(-x) by sin(x) you are actually multiplying two vectors of the same size and is not mathematically correct. That is the reason you are getting the error.
In order to perform an acceptable operation (which is multiplication of values of two vectors but element by element) you need to change it to the following format:
x = linspace(0,4*pi,100);
y = exp(-x) .* sin(x);
.* does the element by element multiplication and, just for your own records, in the same fashion ./ does element by element division.
I hope it helped.

Related

Matlab ./ sign; basic matlab

I am a newbie to Matlab and am trying to figure out code. One thing that keeps returning and confusing me is the ./ sign. I tried googling and stackoverflowing it, but I can not find any documentation on it. Just googling ./ in combination with Matlab does not get me there.
To my understanding the code in the bottom does: Take the first record of the contry.farm.potatoes and divide this by all country.farm.tractors values summed. The result however is always a 0.x numbers. So from 0 to 1. Does that mean that the ./ sign makes sure it is a percentage?
country.farm.potatoes(1,:)./sum(country.farm.tractors,1)
General explanation
the following code does the following:
(1) takes the first row of country.farm.potatoes
(2) generate a vector such that the i'th coordinate is the sum of the i'th column of country.farm.tractors
(3) divides each coordinate of (1) by the corresponding coordinate in (2).
(:,1) syntax
Given a matrix M of size m,n, the syntax '(:,1)' extracts the first row of the matrix.
It generates a row vector of size 1xn.
M(1,:)
sum(M,1) syntax
Given a matrix M of size m,n, the syntax sum(M,1) generates a row vecotr of size 1xn,
s.t each coordinate j is the sum of the j'th column of the matrix.
sum(M,1)
A ./ B syntax
Given two matrices or vectors A,B (of same size), the syntax 'C=A./B' yields a per coordinate division result.
This means that C(i,j)=A(i,j)/B(i,j)
C = A./B
for example:
[9,6,2] ./ [3,3,2]
ans = 3 2 1

Assume that x, y, and z are Matlab arrays, plot the function e^(-x)sin(x) across the interval [0. 4pi]

x=linspace(0, 2*pi, 100);
y=sin(x);
z=exp(-x);
Given that x, y, and z are already initialized, how do I write a function that plots exp(-x)sin(x) across the interval [0, 4pi] without additional calls to sin or exp? Just need some help getting started.
Thanks to #Rayryeng for getting me started. I believe the following command more closely satisfies the question's specifications.
plot(x+x, z.*z.*y)
Well, you've already created arrays for sin and exp stored in y and z respectively. These arrays were created on the same domain as x. You just need to multiply both arrays together element-wise and plot the graph. It's as simple as doing:
plot(x, z.*y);
Here, .* stands for element-wise multiplication. If you were to do z*y, MATLAB interprets this as matrix multiplication where z and y are interpreted to be matrices. This is obviously not what you want.
However, your array of x only contains points from 0 to 2*pi. If you want to plot this from 0 to 4*pi, you have to modify your call to linspace:
x=linspace(0, 4*pi, 100); %// Change
y=sin(x);
z=exp(-x);
plot(x, z.*y);
Now, x will contain 100 points between 0 to 4*pi. For more information on basic MATLAB operations, check out this link: http://www.mathworks.com/help/matlab/matlab_prog/array-vs-matrix-operations.html. What you have asked falls into the basic realms of array and matrix operations.
Edit
In the spirit of your question, we can't modify linspace. You did something clever where we can simply scale our values of x by 2 or adding with x so that we have points going from 0 to 2*pi to 0 to 4*pi. Also, if we scale our points by 2, this means that our input argument into the function must also be scaled by 2. So, the final function we need to plot is:
y = exp(-2x)*sin(2x)
Noting your hint, exp(-2x) = exp(-x-x) = exp(-x)exp(-x). Further, note that sin(2x) performs a compression by a factor of 2 (tip of the hat goes to knedlsepp for noticing my blunder). Due to the periodic nature of sin(x), we know that elements will repeat after 2*pi, and so if you want to go to 4*pi, simply subsample y by a factor of 2 and then append these same elements to a new vector. Therefore, our expression for the function simplifies to:
y = exp(-x)exp(-x)sin(2x)
This leads to the answer alluded to knedlsepp:
plot(x+x, z.*z.*[y(1:2:end) y(1:2:end)]);
As such, you should consider changing your edits to match this answer instead. It isn't quite right with respect to the sin(x) part in your code.

MATLAB: element-wise multiplication of two matrices over one index?

I'm trying to figure out if there's a native way of obtaining a certain kind of element-wise product of two matrices in Matlab.
The product that I'm looking for takes two matrices, A and B say, and returns there product C, whose elements are given by
C(i,j,k) = A(i,j)*B(j,k)
Naturally, the number of columns of A is assumed be the same as the number of rows of B.
Right now, I'm using the following for-loop (assuming size(A,2)==size(B,1) is true). First, I initialize C:
C = zeros(size(A,1), size(A,2), size(B,2));
And then I perform element-wise multiplication via:
for i=1:size(A,2)
C(:,i,:) = A(:,i)*B(i,:);
end
So, my question is: Is there a native way to this sort of thing in Matlab?
You need to "shift" the first two dimensions of B into second and third dimensions respectively with permute and then use bsxfun with #times option to operate on A and the shifted dimension version of B -
C = bsxfun(#times,A,permute(B,[3 1 2]))

Using matlab to manipulate each element in a vector without a for loop

I'm trying to write some code in matlab that will manipulate each element in a vector and will also return a vector. So basically if I have a vector x = [1 2 3 4 5]'; I would like to perform 2 * x(i) * i, where i is the ith element in the vector. And return y = [2 8 18 32 50]';
Right now I have the code:
N = length(x);
for i=1:N
y(i,:) = (i*2).*x(i,:);
end
I've new to Matlab so I've been doing research to try and learn the syntax that will let me do element by element multiplication and all that but it's been difficult. I can't get past that 1:numel(x) takes the place of my i. Again I'm new to matlab so any explanation on the answers that will help me learn is greatly appreciated. Thanks!
Here is how to do it:
y = x.*(1:numel(x))*2
Here is why: Often we want to do an operation to every element in a vector or matrix. Matlab will allow you to do this with element-wise operations. For example, suppose you want to multiply each entry in vector x with its corresponding entry in vector y. In other words, x(1)*y(1), x(2)*y(2),etc. in order to do this, one should use the symbol . before the multiplication. In fact, you can put a . in front of any math symbol to tell Matlab that you want the operation to take place on each element of the vector or matrix.

RBF and pseudoinverse XOR

The problem i am trying to understand is easy but i cant seem to get the correct result in matlab. The actual problem is that i want to get the weight vectors of a 2 hidden layer input RBF using just the plain distance as a function, i.e. no Baysian or Gaussian function as my φ. I will use the function with 2 centres let's say 0,0 and 1,1. So this will give me a Matrix φ of:
[0 sqrt(2) ; 1 1; 1 1; sqrt(2) 0] *[w1; w2] = [0;1;1;0] As defined my the XOR function.
When i apply the pseudoinverse of the Φ in matlab * [0;1;1;0] though i get [0.33 ; 0.33] which is not the correct value which would allow me to get the correct output values [0;1;1;0].
i.e. .33 * sqrt(2) != 0 .
Can someone explain to me why this is the case?
I'll take a swag at this. The matrix, I'll call A, A = [0 sqrt(2) ; 1 1; 1 1; sqrt(2) 0] has full column rank, but not full row rank, i.e. rank(A) = 2. Then you essentially solve the system Ax = b, where x is your weighting vector. You could also just do x = A\b in Matlab, which is supposedly a much more accurate answer. I get the same answer as you. This is a very rough explanation, when your system can not be solved for a certain solution vector, it means that there exists no such vector x that can be solved for Ax = b. What Matlab does is try to estimate the answer as close as possible. I'm guessing you used pinv, if you look at the Matlab help it says:
If A has more rows than columns and is not of full rank, then the overdetermined least squares problem
minimize norm(A*x-b)
does not have a unique solution. Two of the infinitely many solutions are
x = pinv(A)*b
and
y = A\b
So, this appears to be your problem. I would recommend looking at your φ matrix if possible to come up with a more robust system. Hope this is useful.