How can I return only part of a matrix from a function, inline?

11 views (last 30 days)
I want to return part of a matrix from a function without saving the entire matrix. The way I currently do this is to define the matrix, then call the portion in a second instance.
a = rand(3);
a = a(:,1);
But I would like to be able to do something like,
a = rand(3)(:,1);
where I only save the portion of interest and disgard the rest. This is something I do in Python frequently but have never figured out how to do it in MATLAB, and I have no idea what search terms to use when trying to find a solution.
Note: This should work on any function that returns a matrix; rand is just an example.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Nov 2018
There is no nice built-in syntax for this: it is not permitted to syntactically index into the results of a function call or expression.
The official solution if you need expression syntax would be to use subsref() to do the indexing.
subsref() is pretty ugly, so I find it must better to use an auxillary function to do the work.
NthCol = @(M, N) M(:,N);
after which you can
a = NthCol(rand(3), 1);
  2 Comments
Stephen23
Stephen23 on 27 Nov 2018
Edited: Stephen23 on 27 Nov 2018
While this does provide a work-around, I doubt that this would allow the JIT engine to optimize the code efficiently. Quite possibly simply allocating to a temporary variable would provide the most efficient solution. It would be interesting to do some tests.
For code clarity and portability reasons I would also avoid doing this: better to learn and use standard MATLAB practices, so that your colleagues do not rue all all of those arcane "shortcuts" when they have to work with your code.
Walter Roberson
Walter Roberson on 27 Nov 2018
A real function rather than an anonymous function would almost certainly be faster:
function selected = NthCol(M, N)
selected = M(:,N);
end

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!