セル配列、構造体、構​造体配列の各要素に対​して、for文を用い​ずに同じ関数を一括し​て適用する方法はあり​ますか?

セル配列、構造体、構造体配列の各要素に対して、for文を用いずに同じ関数を一括して適用する方法はありますか?

 Accepted Answer

MathWorks Support Team
MathWorks Support Team about 6 hours ago
Edited: MathWorks Support Team 8 minutes ago

0 votes

関数 "cellfun" , "structfun" , "arrayfun" を用いることで、データの各要素に任意の関数を一括して適用することができます。
各関数の概要と実行例を下記に示します。
● cellfun :セル配列の各要素に対して関数を適用
● structfun:構造体の各フィールドに対して関数を適用
● arrayfun :構造体配列を含む配列の各要素に対して関数を適用
(複数の入出力を持つ関数に対しても適用可能)
■セル配列の各要素に対して関数lengthを実行する場合の例
>> cellArray = {'abcde', 3; [5 6], 'mnopqr'}; >> b = cellfun(@length, cellArray) b = 5 1 2 6
■構造体の各フィールドに関数std を適用する場合の例
>> sensorData.sensor1 = [12 34 23 28 43]; >> sensorData.sensor2 = [14 38 44 38 56]; >> result = structfun(@std, sensorData) result = 11.6404 15.2971
 ■構造体配列のDataフィールドに5より大きな値を含むかどうかを調べる例
>> sArray(1).Data = [12 5 10]; >> sArray(2).Data = []; >> sArray(3).Data = [4]; >> sArray(4).Data = [12]; >> output = arrayfun(@(y) ~isempty(find(y.Data > 5)), sArray) output = 1 0 0 1

More Answers (0)

Categories

Find more on データ型 in Help Center and File Exchange

Products

Release

R2006a

Community Treasure Hunt

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

Start Hunting!