0

Is there a way to pass the inputs in varargin to fprintf within a loop?

For example if you have something like:

    function = func_name(var1,varargin)
    for i = varargin
        fprintf('The first name is %s , another is %s',var1,varargin)
    end

If the inputs are name1 name2 and name3, I want the loop to output:

    The first name is name1, another is name2 
    The first name is name1, another is name3

fprintf can't take cell inputs, and changing varargin to varargin{:} (making it a separated list) is not exactly what I want either because it doesn't separate out the varargin inputs into separate loops.

I also can't use inputname() because if the input is an expression rather than a single variable, Matlab returns an empty string '' when calling input name. Is there some way to still use inputname() and add a counter to the loop, or to index the varargin inputs and cycle through them?

ali_m
  • 71,714
  • 23
  • 223
  • 298
user2654568
  • 47
  • 1
  • 5

1 Answers1

0

When you use for i = varargin, i iterates over the elements of varargin so you can just change the varargin in fprintf statement to i

function = func_name(var1,varargin)
for i = varargin
    fprintf('The first name is %s , another is %s',var1,i)
end

By the way, it is recommended that you avoid using i and j as variables in MATLAB.

Community
  • 1
  • 1
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52