Can a table returned from a function be accessed through indexing immediately?

I have a function of class foo that performs data retrieval from a file and stores it in a table. Let's call this function...
classdef foo
methods
% ...
function t = tbl(this)
% ...
end
end
end
Assuming all things being correct, this function will return a valid table of X rows and Y columns. In order to index it, however, I am encountering some problems...
This appears to be valid:
>> t = foo.tbl();
>> t(:,1);
This appears to be invalid:
>> foo.tbl()(:,1);
Error: Invalid array indexing
Is it possible to index a returned table from the same line as the relevant function call? Or do I have to execute two different lines of code to get these results?

5 Comments

It is certainly possible using SUBSREF... but that should only be used if you wish to obfuscate your code with the intent of confusing and annoying everyone (including yourself) who tries to read and understand your code at a later date.
Indexing on two lines is simple and makes the intent clear.
struct('ok', foo.tbl()).ok(:,1)
This requires a fairly new version of MATLAB. The name of the field, 'ok' is not relevant, as long as it is a valid field name.
Thanks all for the prompt responses. Looks like 2-line indexing will be the way to go.
Not sure why. You said your "function will return a valid table of X rows and Y columns". So let's call that table "t", which you got from t = foo.tbl(). So why can't you just index the table all in one line to get the table value at that location, like I said in my Answer below:
tableContents = t{3, 2} % Get table value at row 3, column 2
@Image Analyst my question isn't about indexing the table's contents all in one line. That's easy. As you said:
tableContents = t{3,2}
But that still implies a previous line that sets the function's returned table to t. The question relates to indexing the table's contents in the same line as the relevant function call.
This generates no errors:
t = foo.tbl();
tableContents = t{3,2}
This generates errors:
tableContents = foo.tbl(){3,2};

Sign in to comment.

 Accepted Answer

You can do it in-line with subsref() and substruct():
subsref(tbl(),substruct('()',{':',1}))
ans = 3×1 table
Var1 ____ 1 2 3
function t = tbl()
t = table([1 2 3].',[4 5 6].');
end

More Answers (1)

Use curly braces to get the contents of a table. Using parentheses gets a table itself.
t = table((1:4)', (10:10:40)')
t = 4×2 table
Var1 Var2 ____ ____ 1 10 2 20 3 30 4 40
t1 = t(3, 2) % A new table, not a number.
t1 = table
Var2 ____ 30
tableContents = t{3, 2} % A number, not a table.
tableContents = 30

Categories

Products

Release

R2021b

Community Treasure Hunt

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

Start Hunting!