Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA el 17 de Jun. de 2020
Comentada: Shojiro SHIBAYAMA el 17 de Jun. de 2020
あるクラス 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 comentarios
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA el 17 de Jun. de 2020
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA el 17 de Jun. de 2020

Iniciar sesión para comentar.

Respuesta aceptada

Shojiro SHIBAYAMA
Shojiro SHIBAYAMA el 17 de Jun. de 2020
次のコードを書くと解決します。
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 comentario
Shojiro SHIBAYAMA
Shojiro SHIBAYAMA el 17 de Jun. de 2020
最終的に、一般の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

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!