0

In matlab I have two vectors, ind and ind3. ind = [1 2 3 4 5] and I want to define ind3 based on ind such that I want ind(3), ind(4) and ind(5) to be ind3(1) and ind3(2) and ind3(3). so that ind3 = [ind(3) ind(4) ind(5)] but for some reason I can't do this. I thought it would be simple to do using nested for loops but it doesn't really work.

for i=3:5
  for n=1:3
    ind3(n,:) = ind(i,:);
  end 
end 

By going through the for-loops logically I know why the output is wrong.. but I don't get how else to do it? Am I being stupid and missing something really simple?!

I know its probably a simple answer but can anybody help??

Thanks.

3
  • 1
    just write ind3(1:3,:)=ind(3:5,:) Commented Feb 21, 2015 at 1:26
  • 1
    so please make the question a bit more clear, do you want to copy, or shift by 2 columns ? Commented Feb 21, 2015 at 1:28
  • @bla no I misunderstood your solution... Its 1.30am and I just misread what you had written.. sorry!! deleted that comment. Commented Feb 21, 2015 at 1:30

3 Answers 3

1

If you want ind3 = [ind(3) ind(4) ind(5)] and you want to do it in a loop you just need a single loop. Additionally, since you're dealing with vectors you just have one indexing variable.

for n=1:3
  ind3(n) = ind(n + 2);
end
Sign up to request clarification or add additional context in comments.

1 Comment

... Thanks... I don't know why it didn't occur to me. Thanks.
0

Maybe I'm misunderstanding your question but is this what u want:

ind3=ind(3:5)

Comments

0

First of all, you said that your arrays are one dimensional (they are not matrices), and in your code by calling ind3(n,:) or ind(i,:) you treat them like 2 dimensional arrays.

As long as everything is 1 dimensional here, you need just one for loop:

for i=3:5
    ind3(i)=ind(i-2);
end

Explanation: here i=3,4,5. For i=3 you assign ind3[3]=ind[1], for i=4: ind3[4]=ind[2], for i=5: ind3[5]=ind[3].

Or you can simply call ind3=ind(3:5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.