MATLAB Question

1. Jul 27, 2009

senthya

1. The problem statement, all variables and given/known data

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]

3. 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..

2. Jul 27, 2009

Feldoh

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?

3. Jul 28, 2009

MATLABdude

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 [Broken]

Last edited by a moderator: May 4, 2017
4. Jul 28, 2009

senthya

Feldoh: thank you for your comment..

MATLABdude : thank you for your help but i still don't know how to solve this problem because im 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
end

Please tell ma how to solve it..
with respect to you..

5. Jul 28, 2009

MATLABdude

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).

6. Jul 28, 2009

Feldoh

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?