Can a table returned from a function be accessed through indexing immediately?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Samuel Weise
am 4 Feb. 2022
Kommentiert: Samuel Weise
am 7 Feb. 2022
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
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
Akzeptierte Antwort
Voss
am 4 Feb. 2022
You can do it in-line with subsref() and substruct():
subsref(tbl(),substruct('()',{':',1}))
function t = tbl()
t = table([1 2 3].',[4 5 6].');
end
0 Kommentare
Weitere Antworten (1)
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)')
t1 = t(3, 2) % A new table, not a number.
tableContents = t{3, 2} % A number, not a table.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!