Extract values from matrix/cell in single step

7 views (last 30 days)
I'm sure there's a nice way of doing this in a single line, just haven't found the right syntax... If I have a several element matrix, how can I extract values from it in one step - specifically, I'm looking to take the screensize available in X & Y...
Size = get(groot,'ScreenSize')
returns a 1x4 double, and I then can access each element as standard Matlab Matrix Indexing:
X_Size = Size(1,3);
Y_Size = Size(1,4);
I'm wanting to do something like the following, which takes the 3 lines into 1:
[Offset_1 Offset_2 X_Size Y_Size] = get(groot,'ScreenSize');
which would assign each of the 4 elements to the 4 variables in the matrix on the left. What's the best practice to do this?

Accepted Answer

Jan
Jan on 8 Nov 2016
Edited: Jan on 8 Nov 2016
The best practize is not to try to pack all processing into single lines. One-liner are appealing, but they are not necessarily efficient, most of all when you take into account the readability of the code. Because debugging is often more time consuming than the run time, "optimizing" code to one-liners is not useful.
You could create an own function for such a splitting:
function varargout = Split(X)
if nargout ~= numel(X)
error('Dimensions do not match.');
end
for k = 1:nargout
varargout{k} = X(k);
end
end
Then:
[Offset_1 Offset_2 X_Size Y_Size] = Split(get(groot,'ScreenSize'));
But I prefer the simple stupid:
Size = get(groot,'ScreenSize')
X_Size = Size(1,3);
Y_Size = Size(1,4);

More Answers (1)

Thorsten
Thorsten on 8 Nov 2016
Edited: Thorsten on 8 Nov 2016

Community Treasure Hunt

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

Start Hunting!