Reputation: 213
I have an expression such as s=aU+bV, where a
and b
are scalars and U
and V
3-component vectors. The output s
is clearly a 3-component vector. Let's assume I want to plot the first component of s
find out how this varies when I change a
and b
.
In order to plot I have to use surf, which takes matrices for the variables a
b
. So I attempt to create matrices with meshgrid
:
A=0:10;
B=1:10;
[a,b]=meshgrid(A,B);
U=[1,1,0];
V=[1,0,1];
s = a*U + b*V;
This clearly doesn't work, because nor the matrix product nor the element-wise product are well defined in this case. How do I actually make the matrices which represent the grid a
b
multiply element-by-element the vectors U
and V
?
Upvotes: 1
Views: 785
Reputation: 30046
You want to use element-wise multiplication (.*
) because you still want to treat a
and b
as scalars (i.e. use each element individually).
You can make a 3D output, where each 2D slice corresponds to your meshgrid
output, with one slice per component of U
and V
. Therefore in this example getting a 10*11*3
matrix.
To do this, just reshape
the U
and V
vectors to be 1*1*3
in size
U = reshape( [1,1,0], 1, 1, [] ); % Or equivalently U(1,1,:) = [1,1,0]
V = reshape( [1,0,1], 1, 1, [] ); % Or equivalently U(1,1,:) = [1,0,1]
Then do element-wise multiplication
s = a.*U + b.*V;
Note: before MATLAB R2016b (when implicit expansion was introduced) you'll have to use bsxfun
to get the equivalent:
s = bsxfun( @times, a, U ) + bsxfun( @times, b, V );
You can then plot the i
th element of S
changing with A
and B
by plotting s(:,:,i)
.
Upvotes: 3
Reputation: 4768
You could do it using a 3D matrix:
[A,B] = meshgrid(0:10,1:10);
U(1,1,:) = [1,1,0];
V(1,1,:) = [1,0,1];
s = A.*U + B.*V;
% s is now a NxMx3 matrix, where N = length(A) and M = length(B)
% We can plot how s varies with a and b as follows
surf(A,B,s(:,:,1)); % first component
surf(A,B,s(:,:,2)); % second component
surf(A,B,s(:,:,3)); % third component
Upvotes: 1