Reputation: 2403
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.
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
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:
Is this what you had in mind?
Upvotes: 1