Shifting Vector Elements Left in MATLAB

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 3K views
senthya
Messages
2
Reaction score
0

Homework Statement



you are given a vector y construct a MATLAB script program to shift all element of y left by ( n ) position..

I mean if y=[1 5 6 9 3]
and n=2

by apply this program on y we have :

y=[3 1 5 6 9]


The Attempt at a Solution



this is my Attempt to solve this problem :

x=input('x= ')
n=input('n= ')
for i=1:n
x(i)=1;
while x(i)+1<=n
x(i)=x(i)+1;
end
end
x

I know its wrong ..to that reason i need your help..
 
Physics news on Phys.org
x(i) = 1 is changing your data into a string of 1's

while x(i)+1<=n -- This actually checks to see if the value of x(i) + 1 <= n. I'm not sure how this helps you?
 
Welcome to PhysicsForums, senthya!

Here are some hints:
You need to do index shifting
prod(size(matrix_A)) gives the number of elements in matrix_A

You can use many C/C++ constructs in MATLAB, including if, while, for:
http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/f4-1931.html
 
Last edited by a moderator:
Feldoh: thank you for your comment..

MATLABdude : thank you for your help but i still don't know how to solve this problem because I am just a beginner in MATLAB

I tried again and this is my attempt :

x=input('x= ')
n=input('input n less than x ')
m=length(x)
n=[x(1,n+1:m),x(1,1:n)]
for i=1:20
for j=1:20
if i>=j
a(i,j)=i+j
else
a(i,j)=0
end
end
endPlease tell ma how to solve it..
with respect to you..
 
Your new program is overly complicated and still doesn't solve the problem (also, it just zeros out a bunch of entries--have you actually tried running the script? That should tell you that you've got an error.) Here at PhysicsForums, we don't tell you how to solve a problem, but rather try to guide you through it.

So I suspect that you probably just jumped into the coding for this question without thinking of how to actually do it (don't feel too bad, this is what most new programmers do). Let's start there: if you were doing this by hand, what would you have to do?

Also, for a 1-D array, you don't need to do a(1, index) to address something, you can just use a(index).
 
To further that MATLABdude said, it's always good practice to write out your algorithms in pseudo-code before you try implementing them.

That said let's talk through it a little bit:
You want to take a 1-dimensional matrix (row vector) and you want to move the values n spaces:

In other words you are trying to make a new vector b(i) such that: b(i+n) = a(i) for all i

What's your next step in logically doing this going to be?