Can a table returned from a function be accessed through indexing immediately?
Show older comments
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.
Walter Roberson
on 5 Feb 2022
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.
Samuel Weise
on 7 Feb 2022
Image Analyst
on 7 Feb 2022
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
Samuel Weise
on 7 Feb 2022
Accepted Answer
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)')
t1 = t(3, 2) % A new table, not a number.
tableContents = t{3, 2} % A number, not a table.
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!