MATLAB Answers

Indexing of fresh array in one line without intermediate variable.

205 views (last 30 days)
Maxim on 6 Jun 2013
Commented: Walter Roberson on 6 Feb 2020
How do I index a newly made array without intermediate variables?
Maybe not the best example, but imagine I want to do this
How do I do it in one line?
It is not a regexp question. This problem occurs in many different situations. Thank you
EDIT Another example
function ans = Func(array)
I want it to look like
But I need to do
temporary = Func(1:10);
UniqueWorldline on 14 Nov 2017
For anyone finding this question as late as I have, but who is looking for a simple solution for the
function, do the following to only get the one index of the array size you are looking for:
A = [1,2,3,4,5]; % Some array
arrayCols = size(A); % This returns a 1x2 array with the number of rows
% and columns of A. Which is undesirable if only
% the columns are wanted. Instead do this:
[arrayRows,arrayCols] = size(A);
Now arrayCols is a scalar value that can be used immediately. This doesn't allow you to do
but it can still eliminate an intermediate.

Sign in to comment.

Accepted Answer

Maxim on 6 Jun 2013
Edited: Maxim on 6 Jun 2013
Solution 1
value = subsref(magic(5),struct('type','()','subs',{{3,3}}));
Solution 2
paren = @(x, varargin) x(varargin{:});
paren(magic(5), 3, 3);
Walter Roberson
Walter Roberson on 6 Feb 2020
MATLAB does "really" support execution and indexing in the same line, but the syntax for it is pretty ugly. And you need a real assignment in order to capture any output after the first output from a function that returns multiple outputs.

Sign in to comment.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 6 Jun 2013
Edited: Azzi Abdelmalek on 6 Jun 2013
Look at
a=[2 3 5 8]
out=arrayfun(@(x) x^2+sin(x),a)
  1 Comment
Maxim on 6 Jun 2013
I know these functions, but don't see how they could be helpful. The problem is that I can't index the fresh array.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!