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

1 Ansicht (letzte 30 Tage)
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 Kommentare
Image Analyst
Image Analyst am 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
Samuel Weise am 7 Feb. 2022
@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};

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Voss
Voss am 4 Feb. 2022
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

Weitere Antworten (1)

Image Analyst
Image Analyst am 5 Feb. 2022
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

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by