Ahaan S. Rungta
Ahaan S. Rungta

Reputation: 2403

Changing the coordinates using a vector

Let's say I am at the point (0, 0) in MATLAB and I want to move in the coordinate plane, let's say by the vector [1, 1]. Clearly, I could just manually add 1 and 1 to the x and y coordinates, or I could set v = [1, 1] and increment x by v(1) and y by v(2) or something along those lines. However, let's say I didn't want to do this. For example, suppose my aim is to plot the graph generated by the following algorithm.

  1. Start at the point (0, 0)
  2. Alternate between the displacement vectors (1, 1) and (1, -1) until you reach (100, 0).
  3. Graph it.

How would I do this using the vector directly? In other words, is there something in MATLAB which allows you to directly do something like position = current position + vector? Thanks!

Upvotes: 0

Views: 94

Answers (1)

Benoit_11
Benoit_11

Reputation: 13945

Here is a way to do it from what I understood:

clc
clear

%// The 2 displacement vectors
d1 = [1 1];
d2 = [1 -1];

%// Create a matrix where each row alternates between d1 and d2. 
%// In the following for-loop we will access each row one by one to create the displacement.

D = repmat([d2;d1],51,1);

%/ Initialize matrix of positions
CurrPos = zeros(101,2);

%// Calculate and plot
hold all
for k = 2:101

    CurrPos(k,:) = CurrPos(k-1,:) + D(k,:); %// What you were asking, I think.

    %// Use scatter to plot.
    scatter(CurrPos(k,1),CurrPos(k,2),40,'r','filled')

end

box on
grid on

And the output:

enter image description here

Is this what you had in mind?

Upvotes: 1

Related Questions