インスタンスメソッド​の第2出力をcell​funで取得する方法

조회 수: 2 (최근 30일)
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA 2020년 6월 17일
댓글: Shojiro SHIBAYAMA 2020년 6월 17일
あるクラス SomeClass のインスタンスメソッドが2つ変数を返すときに、cellに SomeClass のインスタンスを初期化して保存しておいて、cellfunでまとめて実行する方法はありますか?
以下のようなコードを書いています。
X; % some data
objs(:) = {SomeClass()}; % initialize
[~, ret] = objs{1}.predict(X); % predict
% bulk execution
cellfun(@(x)x.predict(X), objs)
例えば load 関数では、出力を構造体で渡すことができるので次のように書くことができます。第2引数の取得とは異なりますが、以下のような挙動を、第2引数でも実行したいです。
filepaths = {'path1', 'path2', 'path3', ...};% file paths
data = cellfun(@(f) {load(f)}, filepaths);
data{1} %=> returns a structure having all variables in `path1` file.
うまく説明できていないかもしれませんがよろしくおねがいします。
解決策(案、あまりやりたくない):
第2出力だけを出力するインスタンスメソッドを定義する
  댓글 수: 2
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA 2020년 6월 17일
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA 2020년 6월 17일

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

채택된 답변

Shojiro SHIBAYAMA
Shojiro SHIBAYAMA 2020년 6월 17일
次のコードを書くと解決します。
function out = out2(fun, varargin) % gets the second output argument of anonymous function fun
[~,out] = fun(varargin{:}); % fun must have no input arguments
end
あるいは、一般の第N出力に対して
function out = outN(fun, N, varargin)
eval(['[' repmat('~,', 1, N) 'out] = fun(varargin{:});']);
end
と書くといけそうです。
  댓글 수: 1
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA 2020년 6월 17일
最終的に、一般のN(>=2)に対して次のように書けます。
function out = outN(fun, N, varargin)
% >> [A,B]=ismember(1,[0,1,2,3,4,5])
% A =
% logical
% 1
% B =
% 2
% >> outN(@ismember,2,1,[0,1,2,3,4,5]) % get the second output
% ans =
% 2
assert(N>=2,"indicate after 1st output");
omit = cell(1, N-1);
omit(:) = {'~'};
ignore = join(omit, ',');
eval(['[' ignore{1} ',out] = fun(varargin{:});']);
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB でのオブジェクト指向デザイン에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!