Solving MATLAB Meshgrid: A Beginner's Guide

  • Thread starter Thread starter cookiemnstr510510
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 3K views
cookiemnstr510510
Messages
162
Reaction score
14
Homework Statement
The area of a rectangle is length times width. Find the areas of rectangles with lengths of 1,3, and 5cm and with widths of 2,4,6 and 8cm. (you should have 12 answers)
Relevant Equations
meshgrid command in MATLAB
Hello All,
So I know how to solve this problem, but I don't understand it.
I first create a vector for length and width:
L=[1 3 5]
W=[2 4 6 8]
I then use meshgrid to make my L and W vectors have the same dimensions.
[X,Y]=meshgrid(L,W)
Then multiply X and Y together using array multiply (not matrix multiply)
X.*Y

This seems like magic to me.
I know Meshgrid defines X so every row is L, and each of Y's columns is W. I also know that the dimensions of both X and Y have rows equal to length(W) and columns equal to length(L).

I get all that and accept what Meshgrid does internally, I just wonder if there is a logical sort of "proof" of how we get the correct answer from it. It seems a bit convoluted to me as a beginner, and difficult to think about.

Any help is appreciated!
Thanks
 
on Phys.org
The point of meshgrid(X, Y) is to pair every value in X with every value in Y, which is exactly what you want to do.

Suppose you wanted to write out by hand all those combinations of L and W as ordered pairs.
L=[1 3 5]
W=[2 4 6 8]
You might write something like this:
(1, 2) (1, 4) (1, 6) (1,8)
(3, 2) (3, 4) (3, 6) (3, 8)
(5, 2) (5, 4) (5, 6) (5, 8)
There's an array of first values there that looks like this:
1 1 1 1
3 3 3 3
5 5 5 5
and an array of second values that looks like this:
2 4 6 8
2 4 6 8
2 4 6 8

The whole point of meshgrid is to generate those arrays, so that when you match them up element by element you get all the possible combinations in the order you put in.

So when you store those as X and Y, and you multiply them together element by element, you've multiplied every length by every width.
 
  • Like
  • Informative
Likes   Reactions: cookiemnstr510510 and marcusl