How do I make this 2 dimensional vector follow a formula

1 view (last 30 days)
I want elements in a 2 dimensional vector two to follow a formula given its location (x,y) in the vector. For example, I want the formula to be like: "element" = 6xy+x+1. So if I looked at the 3rd position across and the 2 element down then it would say 40 because 6(3)(2)+3+1=40. I know that I can do this using 2 for loops but I was hoping for a more efficient way to do it.

Accepted Answer

David Goodmanson
David Goodmanson on 16 Jan 2017
Edited: David Goodmanson on 16 Jan 2017
Hello Jesse, The standard way to do this is with the meshgrid function:
x = 1:10; % or whatever size it is
y = 1:10; % same comment
[xx yy] = meshgrid(x,y);
z = 6*xx.*yy+xx+1;
You have to use .* (dot multiply) in the appropriate places so the multiplication is term-by-term. In your case it looks like you want the x and y vectors to just be consecutive integers but in general x and y could have any values and do not even have to be sorted.

More Answers (0)

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!