Further simplify a simple vectorized operation
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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 个评论
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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!