PROBLEMS WITH TWO VARIABLES Matlab

All of the calculations we have done thus far have used only one variable. Of course, most physical phenomena can vary with many different factors. In this section, we consider how to perform the same calculations when the variables are represented by vectors.

Consider the following MATLAB ®

statements:

x = 3;

y = 5;

A = x * y

Since x and y are scalars, it’s an easy calculation: x· y= 15, or

A =

15

Now, let’s see what happens if x is a matrix and y is still a scalar:

x = 1:5;

returns five values of x . Because y is still a scalar with only one value (5),

A = x * y

returns

A =

5 10 15 20 25

This is still a review. But what happens if y is now a vector? Then

y = 1:3;

A = x * y

returns an error statement:

??? Error using = => *

Inner matrix dimensions must agree.

This error statement reminds us that the asterisk is the operator for matrix mul-tiplication, which is not what we want. We want the dot-asterisk operator ( .* ), which will perform an element-by-element multiplication. However, the two vectors, x and y , will need to be the same length for this to work. Thus,

y = linspace(1,3,5)

creates a new vector y with five evenly spaced elements:

y =

1.0000 1.5000 2.0000 2.5000 3.0000

A = x .* y

A =

1 3 6 10 15

Leave a Reply

Your email address will not be published. Required fields are marked *