Further simplify a simple vectorized operation

조회 수: 1 (최근 30일)
Christopher
Christopher 2014년 3월 9일
댓글: the cyclist 2014년 3월 9일
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?

채택된 답변

the cyclist
the cyclist 2014년 3월 9일
편집: the cyclist 2014년 3월 9일
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
Christopher
Christopher 2014년 3월 9일
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 2014년 3월 9일
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".

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2014년 3월 9일
Nothing that I can see. It should work.
  댓글 수: 1
Christopher
Christopher 2014년 3월 9일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by