Since when has it been possible to dot-index the output of a class method?

조회 수: 2 (최근 30일)
Since when has it been possible to directly dot-index the output of a class method call, like this -
classdef myClass
properties
p
end
methods
function obj=myClass(val)
obj.p=val;
end
function obj=increment(obj)
obj.p=obj.p+1;
end
end
end
obj=myClass(2)
obj =
myClass with properties: p: 2
obj.increment.p
ans = 3
And why then, it is still not possible to do something similar with function calls -
subfunc.a
Error: File: test.m Line: 1 Column: 1
Using the dot operator to index into the output of function 'subfunc' is not
supported.
function S=subfunc()
S.a=1;
S.b=2;
end
  댓글 수: 1
Matt J
Matt J 2022년 5월 18일
Quite intriguing. It works with brace indexing, too:
classdef myClass
properties
p
end
methods
function obj=myClass(val)
obj.p=val;
end
function out=num2cell(obj)
out=num2cell(obj.p);
end
end
end
obj=myClass([30,10,70]);
obj.num2cell{1}
ans = 30
obj.num2cell{3}
ans = 70

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2022년 5월 19일
Since R2019b.
Indexing: Use dot indexing into function calls
You can now use dot indexing to index into the result of a function call. MATLAB evaluates the function and then applies the dot indexing operation to the result.
For example, this function creates a structure:
function out = createStruct(in)
out = struct("aField", in);
end
You can call this function and immediately access the structure field it creates:
createStruct(3).aField
For more information, see Indexing into Function Call Results.
  댓글 수: 7
Walter Roberson
Walter Roberson 2022년 7월 21일
Oh, of course, that second example thinks it is indexing into a variable named 'struct', makes more sense now.
Bruno Luong
Bruno Luong 2022년 7월 21일
It does not do what you want but it runs without error
figure(gcf().Number).Name = 'hello'
figure = struct with fields:
Name: 'hello'

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by