Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Help with vector operations

Subject: Help with vector operations

From: Adam

Date: 9 Nov, 2011 12:20:31

Message: 1 of 2

Hi,

I am having trouble with a very simple concept. I'd like to optimize some for loops I've created but can't seem to understand why my vector operations won't work. Here is a very simple example of what I'm trying to do:

a=[1,2,3,4,5,6];
b=[1,2,3,4,5,6];
c(1)=1;

c(2:3)=a(2:3)-c(1:2);

I get the error "index exceeds matrix dimensions". I believe the error is in computing c(3), as it does not know c(2) yet? However, when I loop this as follows I get no error:

a=[1,2,3,4,5,6];
b=[1,2,3,4,5,6];
c(1)=1;

for i=2:3
c(i)=a(i)-c(i-1);
end

Why can I use the loop but not the vector operation? This is probably very simple but I can't seem to find an explanation anywhere. Can anyone offer some help? Thanks in advance!

Subject: Help with vector operations

From: Tim Love

Date: 9 Nov, 2011 13:02:12

Message: 2 of 2

> Why can I use the loop but not the vector operation?

Because the loop determines the order that the operations are run in. The loop boils down to "c(2)=a(2)-c(1); c(3)=a(3)-c(2);" which is ok. As you say, in the vectorized version you can't make assumptions about the order of operations, so having c(2) on the RHS is a problem.

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us