Why the valid looking statement gives error in MATLAB? - matlab

It's from this question。
Why the two solutions doesn't work, though it looks very valid for me:
>> t = -pi:0.1:pi;
>> r = ((sin(t)*sqrt(cos(t)))*(sin(t) + (7/5))^(-1)) - 2*sin(t) + 2 ;
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> t = -pi:0.1:pi;
>> r = ((sin(t).*sqrt(cos(t))).*(sin(t) + (7/5)).^(-1)) - 2*sin(t) + 2 ;
>> plot(r,t)
??? Error using ==> plot
Vectors must be the same lengths.
What's wrong with the above?

The * operator is the matrix multiplication operator, which requires its operands to have matching inner matrix dimensions. The .* operator is the element-wise multiplication operator, which requires its operands to have the same size (or for one to be a scalar) so it can perform multiplication on each matching pair of elements. See this link for more detail.
Also, I don't get the plotting error you do when I run the second solution. I just get this warning:
Warning: Imaginary parts of complex X and/or Y arguments ignored

Related

Matlab ??? Error using ==> mldivide Matrix dimensions must agree

I have codes like these in Matlab
...
Kx=cell(10,10,10);
Kx2=cell(ee_max)
bX=cell(10,10)
bX2=cell(ee_max)
...
Kx{ee,ii,jj}=(1/36*VX{ee})*(alphX{ee,x}*bX{ee,ii}*bX{ee,jj}+alphX{ee,y}*cX{ee,ii}*cX{ee,jj}+alphX{ee,z}*dX{ee,ii}*dX{ee,jj})+VX{ee}*1/20*betaX{1+delXX{ii,jj}};
bX{ee,ii}=VX{ee}*(1/4)*f{ee}
...
Kx2{ee}=Kx{ee,:};
bX2{ee}=bX{ee,:};
phi_next=cell(4,4);
...
phi_next{ee}=bX2{ee}/Kx2{ee}
....
I got error at this line
phi_next{ee}=bX2{ee}/Kx2{ee}
as
??? Error using ==> mldivide
Matrix dimensions must agree.
so,what should I do?
regards
Use ./ instead of /.
The code is not complete so you may have other errors with other matrices dimensions.
If you find other errors you may use .* instead of * also when you multiply matrices with different dimensions.
Example:
A: 3 rows, 4 columns
B: 2 rows, 4 columns
C: 4 rows, 1 column
You can use * to multiply A and C (3x4)(4x1) or B and C (2x4)(4x1).
However you need .* to multiply A and B (3x4)(2x1).

Plotting equally spaced points for a graph on MATLAB

The function I need to plot is y = exp(-0.3*t)*(2*cos(2*t) + 4*sin(2*t)) for the range of values of t between 0 and 2*pi.
I entered the following commands on MATLAB:
>> t=linspace(0,2*pi,101);
>> y=exp(-0.3*t)*(2*cos(2*t) + 4*sin(2*t));
And I come up with the following error:
Error using *
Inner matrix dimensions must agree.
I don't know why. Can someone point out why and suggest the correct command line argument?
Thanks!
Your issue is in this term:
exp(-0.3*t) * (2*cos(2*t) + 4*sin(2*t));
You are multiplying 2 vectors. You want to be doing element-wise operations, i.e. each element of exp(-0.3*t) times each corresponding element of (2*cos(2*t) + 4*sin(2*t)), rather than the vector product of the two.
To achieve what you want, simply add a dot . before the multiplication *, like so
y = exp(-0.3*t) .* (2*cos(2*t) + 4*sin(2*t));
See this documentation for array vs. element-wise operations: http://uk.mathworks.com/help/matlab/matlab_prog/array-vs-matrix-operations.html
The "*" operator is a matrix-multiplication operator, like https://en.wikipedia.org/wiki/Matrix_multiplication
You need to use an ".*" operator which is a per-element operator. You must use it to match elements from one vector or matrix to the elements from the other vector or matrix one-to-one.
So you have to do
y=exp(-0.3*t).*(2*cos(2*t) + 4*sin(2*t));
Note that ".*" is not needed when multiplying by constant, because the effect is the same for matrix and per-element operation

A^t * A won't work in matlab?

I'm trying get A^T * A.
but if I try it, I get the error
Error using * MTIMES is not fully supported for integer classes.
At least one input must be scalar. To compute elementwise TIMES, use TIMES (.*) instead.
so I did A^T .* A and it gave me the error
Matrix dimensions must agree.
I don't get it? shouldn't ATA work fine?
A is
A = imread('C:\Users\user1\Documents\MATLAB\5\assignment05_A.jpg');
A = rgb2gray(A);
before trying the multiplication
How do i get a A^T * A matrix??
You can convert to an array of double precision with double then plot with imshow;
A = double(rgb2gray(A));
ATA = A'*A;
imshow(ATA,[]);

Why does my function return two values when I only return one?

So I'm trying to implement the Simpson method in Matlab, this is my code:
function q = simpson(x,f)
n = size(x);
%subtracting the last value of the x vector with the first one
ba = x(n) - x(1);
%adding all the values of the f vector which are in even places starting from f(2)
a = 2*f(2:2:end-1);
%adding all the values of the f vector which are in odd places starting from 1
b = 4*f(1:2:end-1);
%the result is the Simpson approximation of the values given
q = ((ba)/3*n)*(f(1) + f(n) + a + b);
This is the error I'm getting:
Error using ==> mtimes
Inner matrix dimensions must agree.
For some reason even if I set q to be
q = f(n)
As a result I get:
q =
0 1
Instead of
q =
0
When I set q to be
q = f(1)
I get:
q =
0
q =
0
I can't explain this behavior, that's probably why I get the error mentioned above. So why does q have two values instead of one?
edit: x = linspace(0,pi/2,12);
f = sin(x);
size(x) returns the size of the array. This will be a vector with all the dimensions of the matrix. There must be at least two dimensions.
In your case n=size(x) will give n=[N, 1], not just the length of the array as you desire. This will mean than ba will have 2 elements.
You can fix this be using length(x) which returns the longest dimension rather than size (or numel(x) or size(x, 1) or 2 depending on how x is defined which returns only the numbered dimension).
Also you want to sum over in a and b whereas now you just create an vector with these elements in. try changing it to a=2*sum(f(...)) and similar for b.
The error occurs because you are doing matrix multiplication of two vectors with different dimensions which isn't allowed. If you change the code all the values should be scalars so it should work.
To get the correct answer (3*n) should also be in brackets as matlab doesn't prefer between / and * (http://uk.mathworks.com/help/matlab/matlab_prog/operator-precedence.html). Your version does (ba/3)*n which is wrong.

MATLAB operators as functions

I was just curious that whether all operators in MATLAB are internally implemented as functions? We have equivalent functions for almost all MATLAB operators. plus for +, minus for -, eq for == and transpose for '.
Most operators are represented by functions, yes.
A thorough list is provided on the MathWorks page Implementing Operators for Your Class, reproduced here:
a + b plus(a,b) Binary addition
a - b minus(a,b) Binary subtraction
-a uminus(a) Unary minus
+a uplus(a) Unary plus
a.*b times(a,b) Element-wise multiplication
a*b mtimes(a,b) Matrix multiplication
a./b rdivide(a,b) Right element-wise division
a.\b ldivide(a,b) Left element-wise division
a/b mrdivide(a,b) Matrix right division
a\b mldivide(a,b) Matrix left division
a.^b power(a,b) Element-wise power
a^b mpower(a,b) Matrix power
a < b lt(a,b) Less than
a > b gt(a,b) Greater than
a <= b le(a,b) Less than or equal to
a >= b ge(a,b) Greater than or equal to
a ~= b ne(a,b) Not equal to
a == b eq(a,b) Equality
a & b and(a,b) Logical AND
a | b or(a,b) Logical OR
~a not(a) Logical NOT
a:d:b colon(a,d,b) Colon operator
a:b
colon(a,b)
a' ctranspose(a) Complex conjugate transpose
a.' transpose(a) Matrix transpose
command line output display(a) Display method
[a b] horzcat(a,b,...) Horizontal concatenation
[a; b] vertcat(a,b,...) Vertical concatenation
a(s1,s2,...sn) subsref(a,s) Subscripted reference
a(s1,...,sn) = b subsasgn(a,s,b) Subscripted assignment
b(a) subsindex(a) Subscript index
Another good place to look for a list is actually the documentation for bsxfun, which applies any element-wise function with very powerful virtual data replication.
Often useful is vertcat. horizontal vs. vertical concatenation with a comma separated list:
>> c = {'a','b'};
>> horzcat(c{:}) % [c{1} c{2}]
ans =
ab
>> vertcat(c{:}) % [c{1};c{2}]
ans =
a
b
In addition to many other documented operators with named functions (colon,transpose,etc.), there are a couple undocumented ones that you can access with builtin:
parenthesis
>> x = [4 5 6];
>> builtin('_paren',x,[2 3]) % x([2 3])
ans =
5 6
curly braces
>> c = {'one','two'};
>> builtin('_brace',c,2) % c{2}
ans =
two
struct field access (dot)
>> s = struct('f','contents');
>> builtin('_dot',s,'f') % s.f
ans =
contents
However, note that the proper and supported way to use (), {}, or . is via subsref, subasgn, and subindex, depending on the context.
These builtins refer to the operators described in help paren. Also explore the punctuation listed in help punct.
Yes, that's how MATLAB enables operator overloading, by mapping infix operators to named functions.
The documentation lists (by category) the functions invoked by operators. And more here.