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
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
2022년 2월 5일
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
2022년 2월 7일
Image Analyst
2022년 2월 7일
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
2022년 2월 7일
채택된 답변
추가 답변 (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.
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!