フィルターのクリア

variable number of input arguments

3 ビュー (過去 30 日間)
kumar Atishay
kumar Atishay 2020 年 9 月 29 日
コメント済み: Ameer Hamza 2020 年 9 月 29 日
write a function called name_value_pairs that has variable number of input arguments representing name_value_pairs.Naturally,they come in pairs:the first is the name,the next is the value.This means that the function must be called with an even number of actual input arguments. The function returns a single cell array which has exactly two columns:first column contains the name,while the second column contains the values.If function is called with no input argument ,or it is called with an odd number of inputs or if a name is not of char type,the function return an empty cell array. here an example run:
>>db = name_value_pairs('name','john smith','age',32,'children',{'joe','jill'})
db =
3*2 cell array
{'name'} {'john smith'}
{'age'} {[32]}
{'children'} {1*2 cell}

回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 9 月 29 日
編集済み: Ameer Hamza 2020 年 9 月 29 日
You can use varargin
function C = name_value_pairs(varargin)
assert(mod(nargin, 2)==0, 'Number of input arguments must be even.');
C = reshape(varargin, 2, []).';
end
Run it like this
db = name_value_pairs('name','john smith','age',32,'children',{'joe','jill'})
Result
>> db
db =
3×2 cell array
{'name' } {'john smith'}
{'age' } {[ 32]}
{'children'} {1×2 cell }
  2 件のコメント
kumar Atishay
kumar Atishay 2020 年 9 月 29 日
thank you ,but could you solve it without assert .
Ameer Hamza
Ameer Hamza 2020 年 9 月 29 日
You can use if-block instead of assert line
if mod(nargin, 2)==1
C = {};
return;
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Import and Network Parameters についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by