Further simplify a simple vectorized operation

2 views (last 30 days)
I have a row vector of values 'gridx'. For example:
gridx=[0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5]
I also have a large column vector of values P, which are to act as indices for the vector gridx.
Thus, I can sample P(:,1) and get the corresponding values fro gridx as:
P(:,2) = gridx(P(:,1));
I want to use these values to perform another operation, so I replace it with the result as:
P(:,2)=MX-P(:2);
where MX is a column vector of length P(:,1)).
This works, but I want to shorten the code as:
P(:,2)=MX-gridx(P(:,1));
Unfortunately, this does not work. What is wrong with my syntax?

Accepted Answer

the cyclist
the cyclist on 9 Mar 2014
Edited: the cyclist on 9 Mar 2014
The crux of the issue is that
gridx(P(:,1))
is a row vector (because P is a row vector).
In some cases, like simple assignment statements, MATLAB will allow some wiggle room and transpose the right-hand side of the assignment for you (if the lengths of the vectors match). For example, the following will work:
A = magic(3)
A(:,2) = [1 2 3]
In other cases, like vector math operations, MATLAB is more stringent, requiring an exact match in dimensions as well as length. So, for example, the following gives the same error as you see in your example:
B = [1 2] - [1 2]'
One simple solution in your case is to define gridx as the transpose of how you did it:
gridx=[0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5]'
Then it should work fine.
  4 Comments
Christopher
Christopher on 9 Mar 2014
Thanks, this appears to work. I wonder if this is a syntatic oversight in matlab or if there is a good reason for it to not work with the sampled vector being a row vector.
the cyclist
the cyclist on 9 Mar 2014
I think you might be missing the bigger picture. Would you expect this operation to work?
A = rand(1,2) - rand(2,1)
?
I would not, because the dimensions don't match (even though the lengths do). That is exactly what your code was trying to do. Your MX was a column vector, and your gridx was a row vector. My version corrected that mismatch.
Now, as I said, sometimes MATLAB will be a little less stringent, and "guess" what you meant. But, it can't always do that for you. Sometimes (most of the time!) you need to get the dimensions matched yourself. That is not a "syntactic oversight".

Sign in to comment.

More Answers (1)

Matt J
Matt J on 9 Mar 2014
Nothing that I can see. It should work.
  1 Comment
Christopher
Christopher on 9 Mar 2014
I get a dimension mismatch error between MX and gridx(P(:,1)).
But MX and P(:,1) have the same number of rows. gridx is not the same size but the output should be a number in gridx so it shouldn't matter.
I suspect I need to use something like sub2ind, but I don't know how.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!