views:

104

answers:

1

I am trying to sub-array in MATLAB with no luck.

This is what I am doing:

a = randint(latticeSize, 1, [0 1]);

% a 1st attempt which works but sucks 
localPattern = [a(i-1) a(i) a(i+1)];

The above works fine but I want to generalize it with something like:

% this is how I'd like to do it as more general
localPattern = a(i-1 : i+1);

Is there any difference between the two? A display shows the same result but if I use the different alternatives in my code I get very different results (I get what I want with the 1st one).

In case the rest of the code is needed I can provide it, but if someone can spot something just looking at the above then there's no need.

+1  A: 

Remember: in Matlab (almost) everything is a matrix and has at least two dimensions, even if some of them are "singleton" dimensions. In your case,

[a(i-1) a(i) a(i+1)]

is a row, and

a(i-1 : i+1)

is a column in your case, since a is a column. To get the same results in both cases, you can use

a = randint(1, latticeSize, [0 1]);

or transpose the column

localPattern = a(i-1 : i+1)';

depending on what goes on in the rest of your code.

Generally, [] will concatenate things horizontally, and indexing () will keep the dimensions' "directions" as they were.

You can run this:

a = rand(10, 1) 
i=3 
localPattern = [a(i-1) a(i) a(i+1)] 
localPattern = a(i-1 : i+1) 

and take a look at the output -- this should clarify things.

AVB
+1 with this line --> a = randint(1, latticeSize, [0 1]); you basically gave the solution, so I am marking as answer. I am still not too clear why it's working though as the printout was showing the same results (rows for both) even before I changed that line of code!
JohnIdol
See my last edit above, at the bottom of the answer - I could not put code in a omment properly.
AVB
ok, that's clear. I must have been making confusion when running my tests before. Thanks!
JohnIdol

related questions