필터 지우기
필터 지우기

Problem with an equation

조회 수: 2 (최근 30일)
Alexander Engman
Alexander Engman 2016년 1월 31일
편집: Stephen23 2016년 2월 1일
Hi!
I have a problem writing an equation in Matlab. The variables and the equation look like this:
x=(-3:0.001:3)
y=(-4:0.001:4)
z=cos(x*y)*(1+3*(exp-(x.^2+2*y.^2)))
For me one of the obvious problems is that x and y have different sizes. But surely there is a way around the problem.
The message I recieve is:
Error using * Inner matrix dimensions must agree.
So obviously something is also wrong with the dimensions but I can´t figure it out.
So my question is, how do I write this to make this equation work?
A brief explanation of why this is not working would also be appreciated!
Thank you in advance.

채택된 답변

Stephen23
Stephen23 2016년 1월 31일
편집: Stephen23 2016년 2월 1일
Presumably you are not intending to perform matrix multiplication, but rather element-wise multiplication. Here are two methods to get use element-wise multiplication to get an output, even if the input vectors are different lengths:
x = -3:0.01:3;
y = -4:0.01:4;
% method 1: ndgrid
[X,Y] = ndgrid(x,y);
Z1 = cos(X.*Y).*(1+3*exp(X.^2+2*Y.^2));
% method 2: bsxfun
Z2 = cos(bsxfun(@times,x(:),y)) .* (1+3*exp(bsxfun(@plus,x(:).^2,2*y.^2)));
both of these give exactly the same result:
>> isequal(Z1,Z2)
ans =
1
>> size(Z1)
ans =
601 801
So the Z matrices have numel(x) rows and numel(y) columns. Thus you get an output value for each element in x and y.
Note that I reduced the number of points in the vectors (from 6001 and 8001 to 601 and 801), just to make it easier to work with.
I also removed the minus sign from after the exp fucntion as this is not MATLAB syntax and I have no idea what you intended this to do (it results in a syntax error).
Explanation
It confuses many MATLAB learners that there are different ways to multiply matrices. These different ways have been explained clearly many times on this forum, and in the documentation:
The next topic is how to perform element-wise multiply (or any other element-wise operation) on vectors of different lengths. In short: it is not possible to do this and get a vector the length of the input vectors. What length should the output be? Consider:
[1,2,3] .* [8,9]
as an element-wise operation means:
[1*8,2*9,3*????]
Thus the error. The solution is to either:
  • pad the vectors to the same length
  • Orient the vectors orthogonally and operate over every pair of elements. This is what I showed above.
  댓글 수: 2
Alexander Engman
Alexander Engman 2016년 2월 1일
Thank you so much!
Stephen23
Stephen23 2016년 2월 1일
편집: Stephen23 2016년 2월 1일
My pleasure! You can also accept the answer that best resolves your question. This gives us points and is a small token of gratitude that you can offer us.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by