Use the input arguments to load user-defined .mat files(2xn matrix) in the function.

I am new to matlab
It is necessary to use the input arguments to load different .mat files(2xn matrix) each time the function is used by a user. The number of .mat files to be processed inside the function are also changing, so I used varargout and varargin. For each input, there are 2 output vectors.
As input arguments in varargin can be called by varargin{1}, varargin{2}... I tried to use it to load the files. It did not work.
For example, 2 files that should be executed are Data1.mat, Data2.mat
Outputs will be Ans1,Ans2,Ans3,Ans4.
So I used the following command for the function file (that is saved as Data_function.m)
[Ans1,Ans2,Ans3,Ans4]= Data_function (Data1, Data2)
function varargout = Data(varargin)
A= load ('varargin{1}'); %to load first inputargument file name
Ans1 = A(:,1).*3; %just for example
Ans2 = A(:,2).*4;
B= load ('varargin{2}') %to load first inputargument file name
Ans3 = A(:,1).*3;
Ans4 = A(:,2).*4;
end
This gives an erro: Unable to read file 'varargin{1}'. No such file or directory.
(The files Data1 and Data2 are in the current folder, where the function is saved)
It would be a great help if you could show the right way to load multiple files.

 Accepted Answer

A= load (varargin{1}); %to load first inputargument file name
This assumes that when you called
[Ans1,Ans2,Ans3,Ans4]= Data_function (Data1, Data2)
that Data1 is a variable containing a character vector or string scalar that contains a file name.

3 Comments

Thank you for such a quick reply!
You are right, using following..
function varargout = Data_function(varargin)
A= load (varargin{1});
gives this error,(as the (2xn).mat matrix contains real numbers)
Error using load
Must be a string scalar or character vector.
Error in Data_function (line 4)
A= load (Data1);
sorry for not mentioning the data type before. The .mat files I am trying to import are all '2 x n'matrices which contains 'real numbers'(they are x,y values of different curves).
As I understand from your answer, using varargin to input a .mat file is wrong(?)
Could you please show the right way to feed and read user specific amount of .mat files containing 2xn matrix, thorugh the function? This helps a lot, thank you in advance!
As I understand from your answer, using varargin to input a .mat file is wrong(?)
No, varargin to input a .mat file is fine. Your problem is that when you call
[Ans1,Ans2,Ans3,Ans4]= Data_function (Data1, Data2)
that your Data1 is not a character vector or string scalar at that point in the code.
Okay, so the right way is to call the function is:
[Ans1,Ans2,Ans3,Ans4]= Data_function ('Data1', 'Data2')
Thank you for your help.

Sign in to comment.

More Answers (0)

Products

Release

R2020a

Tags

Community Treasure Hunt

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

Start Hunting!