name value pairs with variable input arguments

13 visualizaciones (últimos 30 días)
malki adil
malki adil el 3 de Feb. de 2022
Editada: Benjamin Kraus el 3 de Feb. de 2022
function db = name_value_pairs(varargin)
n=length(varargin); db ={};
if mod(n,2)~=0 || n ==0
db= {};
elseif ~ischar(varargin(1:2:nargin))
db = {};
else
for i=1:2:n
db(i)=[db; varargin{i} varargin{i+1}]
end
end
end
%this is code that i have written and ii cant understand why it result
% db =
% 0×0 empty cell array

Respuestas (1)

Benjamin Kraus
Benjamin Kraus el 3 de Feb. de 2022
Editada: Benjamin Kraus el 3 de Feb. de 2022
The problem is:
~ischar(varargin(1:2:nargin))
The varargin input will always be a cell-array, so this condition will never be true.
I think what you want is:
~iscellstr(varargin(1:2:nargin))
This will verify that the input is a cell-array whose elements are all character vectors.
But, putting any issues in the code aside, unless I'm missing something, your entire function can be written like this:
function db = name_value_pairs(varargin)
if mod(nargin,2)~=0 || ~iscellstr(varargin(1:2:nargin))
db = {};
else
db = varargin;
end
In addition, unless you require the added validation, your function can be replaced in your code by just wrapping your inputs in curly braces.
db = name_value_pairs('a',10,'b',20);
db2 = {'a',10,'b',20};
% db and db2 will be the same

Categorías

Más información sobre Startup and Shutdown en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by