Combining functions and commands in to one script

I have to provide a script that reads in values from 2 separate files. The script should also provide an output file for the predicted value, given the input data. So I have created 2 functions to read in the input files: flle1 and file2. I then have commands that I ran to combine the info in file1 and file2 so that the combined info from file1 and file2 can be input in to the nftool. I also have commands that I ran to modify file3 in order to use it as target data in the nftool. How do I combine this info (functions, commands, nftool data) in to one script so that I can then run this script such that another file1 and file2 can be provided to give an output file?

4 Comments

Does it have to be a script? If so you will need R2016b or later, otherwise it is not possible to put functions in the same file as a script.
yes, it has to be a script. I'm using R2020b.
In that case you can put all the code you need in a single file. What exactly is the issue you are having?
I wasn't sure how to go about connecting all the info. So I was asking for some guidance. I'm trying your suggestion.

Sign in to comment.

 Accepted Answer

Functions by default don't show their scope variables in the workspace.
Did you have any error while running your code? If you don't, you can just perform a test by not using function in your 1st line.
So, just comment the first line of your code, and check if despx and despy appears in your workspace.
Then, your're performing the pipeline I mentioned before.
% Procedural code
% Here you call your functions
despx = importXfile('yourInput.csv')
despy = importYfile('youInput.csv')
% -------------------
%% Functions section
function x_2 = importXfile(filename, dataLines)
% function code
function y_2 = importYfile(filename, dataLines)
% function code

3 Comments

Thanks a bunch! :=)) No, I didn't have any errors. I didn't realize I wouldn't see the variables of the functions in the workspace. But when I commented the main function, as you said, I did see them appear in the workspace.
The actual issue here is that when you have a function then as soon as the function returns, all local variables will be discarded. If you want the content of the variable outside of the function you should return it from the function and assign to a variable when you do.
Great.
If in the near future you want to check the scope of variables of your functions while running, you can click in the line number so it gets a red square: that's debugging stop. Your code will stop in this line, and all the variables you're creating in the environment of your function will appear in the workspace.
If you have a loop in your function for example, and you create a debug stop in the end of the loop, you can check the behavior of every related variables within the function.
If that helped, please accept the answer. =)
Good coding.
Cheers

Sign in to comment.

More Answers (1)

You can write your pipeline as a regular script, calling your input files, processing, and obtaining your result.
As you're up-to-date with MATLAB, you can write your functions in the end of the script.
% Write your pipeline
myInputFile = myOwnReadFunction(whateverInputArguments);
% Process your data
myResults = processingData(myInputFile);
%% Below, write your functions, in the end of your script:
function data = myOwnReadFunction(input1, input2)
% code what you need
end
function result = processingData(input1)
% code your calculation
end
Cheers

11 Comments

Attempting to work thru this bit by bit. And it may be that I am missing what you pointed out in your feedback. So I have the below code. Why is despx and despy not being created in my workspace?
I've tried commenting and uncommenting the end statements of the functions following https://www.mathworks.com/matlabcentral/answers/2169-define-a-function-in-the-main-program. I've tried using...
importXfile("x.csv");
importYfile("y.csv");
thinking x_2 and y_2 will get created in the workspace. Please let me know what I am missing.
function sample2
despx = importXfile("x.csv");
despy = importYfile("y.csv");
function x_2 = importXfile(filename, dataLines)
%IMPORTFILE Import data from a text file
% X_2 = IMPORTFILE(FILENAME) reads data from text file FILENAME for the
% default selection. Returns the numeric data.
%
% X_2 = IMPORTFILE(FILE, DATALINES) reads data for the specified row
% interval(s) of text file FILENAME. Specify DATALINES as a positive
% scalar integer or a N-by-2 array of positive scalar integers for
% dis-contiguous row intervals.
%
% Example:
% x_2 = importfile("/MATLAB Drive/x.csv", [1, Inf]);
%
% See also READTABLE.
%
% Auto-generated by MATLAB on 01-Nov-2020 13:58:15
%% Input handling
% If dataLines is not specified, define defaults
if nargin < 2
dataLines = [1, Inf];
end
%% Set up the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 30);
% Specify range and delimiter
opts.DataLines = dataLines;
opts.Delimiter = ",";
% Specify column names and types
opts.VariableNames = ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11", "VarName12", "VarName13", "VarName14", "VarName15", "VarName16", "VarName17", "VarName18", "VarName19", "VarName20", "VarName21", "VarName22", "VarName23", "VarName24", "VarName25", "VarName26", "VarName27", "VarName28", "VarName29", "VarName30"];
opts.VariableTypes = ["double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Specify variable properties
opts = setvaropts(opts, ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11", "VarName12", "VarName13", "VarName14", "VarName15", "VarName16", "VarName17", "VarName18", "VarName19", "VarName20", "VarName21", "VarName22", "VarName23", "VarName24", "VarName25", "VarName26", "VarName27", "VarName28", "VarName29", "VarName30"], "TrimNonNumeric", true);
opts = setvaropts(opts, ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11", "VarName12", "VarName13", "VarName14", "VarName15", "VarName16", "VarName17", "VarName18", "VarName19", "VarName20", "VarName21", "VarName22", "VarName23", "VarName24", "VarName25", "VarName26", "VarName27", "VarName28", "VarName29", "VarName30"], "ThousandsSeparator", ",");
% Import the data
x_2 = readtable(filename, opts);
%% Convert to output type
x_2 = table2array(x_2);
%end
function y_2 = importYfile(filename, dataLines)
%IMPORTFILE Import data from a text file
% Y_2 = IMPORTFILE(FILENAME) reads data from text file FILENAME for the
% default selection. Returns the numeric data.
%
% Y_2 = IMPORTFILE(FILE, DATALINES) reads data for the specified row
% interval(s) of text file FILENAME. Specify DATALINES as a positive
% scalar integer or a N-by-2 array of positive scalar integers for
% dis-contiguous row intervals.
%
% Example:
% y_2 = importfile("/MATLAB Drive/y.csv", [1, Inf]);
%
% See also READTABLE.
%
% Auto-generated by MATLAB on 01-Nov-2020 14:14:27
%% Input handling
% If dataLines is not specified, define defaults
if nargin < 2
dataLines = [1, Inf];
end
%% Set up the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 30);
% Specify range and delimiter
opts.DataLines = dataLines;
opts.Delimiter = ",";
% Specify column names and types
opts.VariableNames = ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11", "VarName12", "VarName13", "VarName14", "VarName15", "VarName16", "VarName17", "VarName18", "VarName19", "VarName20", "VarName21", "VarName22", "VarName23", "VarName24", "VarName25", "VarName26", "VarName27", "VarName28", "VarName29", "VarName30"];
opts.VariableTypes = ["double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Specify variable properties
opts = setvaropts(opts, ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11", "VarName12", "VarName13", "VarName14", "VarName15", "VarName16", "VarName17", "VarName18", "VarName19", "VarName20", "VarName21", "VarName22", "VarName23", "VarName24", "VarName25", "VarName26", "VarName27", "VarName28", "VarName29", "VarName30"], "TrimNonNumeric", true);
opts = setvaropts(opts, ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11", "VarName12", "VarName13", "VarName14", "VarName15", "VarName16", "VarName17", "VarName18", "VarName19", "VarName20", "VarName21", "VarName22", "VarName23", "VarName24", "VarName25", "VarName26", "VarName27", "VarName28", "VarName29", "VarName30"], "ThousandsSeparator", ",");
% Import the data
y_2 = readtable(filename, opts);
%% Convert to output type
y_2 = table2array(y_2);
%end
%end
So, it looks like I have created my script combining my functions, commands, and network data. I'm so excited. What do I do now in order to modify my script to allow another user to input a new x.csv, y.csv, and z.csv?
%function hw2
despx = importXfile1("x.csv")
despy = importYfile1("y.csv")
despz = importZfile("z.csv")
xtranspose = despx(:)
ytranspose = despy(:)
[X,Y] = meshgrid(1:30)
M1 = [xtranspose(X(:)),ytranspose(Y(:))]
z_output = reshape(despz.', [], 1)
M2=M1'
[z_output,Xf,Af] = neural_function(M2)
reshapeOutput1 = reshape(z_output, 30, [])'
writematrix(reshapeOutput1,'z_predicted.csv')
%end
If you want to allow your user to select a file, you should not hard-code the file name.
To ask the user to provide a file name you can use uigetfile.
Ok, I think I understand what should happen. I just don't know how to write it. So it seems after I run with hardcoded files, I ask if the user wants to enter files for x and y. If yes, ask for files. If user saids no, end program. (I think disp('User selected Cancel'); would end the program.)
If yes, enter file for x using the code below and then enter file for y. Then assign those values to newX and newY and then process newX and newY with functions and commands.
[file,path] = uigetfile('*.csv');
if isequal(file,0)
disp('User selected Cancel');
else
disp(['User selected ', fullfile(path,file)]);
end
With this code you can ask the user to select a file. That is what you need, right?
What exactly is your question? You have already working code that uses a file name, now you know how you can ask a user for a file name.
Well, you don't need to call uigetfile before the user's choice.
A minimalist approach would be like the following (idea, not code itself)
fprintf('Wanna choose files?\n');
fprintf('y or n >> ')
str = input(prompt, 's');
if str == 'y'
[file, path] = uigetfile('yourExtension');
% go through your code
else
fprintf('back off.')
end
Thanks. This is working. I have the following code. Is there any way to time fprintf('choose x file\n'); so that ReadInFileX = load(fileX) doesn't display so quickly? My concern is, fprintf('choose x file\n'); executes but
[fileX,path] = uigetfile('*.csv'); causes the print statement to get covered up. I need to make sure that they user know which file to enter first.
fprintf('choose x file\n');
[fileX,path] = uigetfile('*.csv');
ReadInFileX = load(fileX)
% go through your code
fprintf('choose y file\n');
[fileY,path] = uigetfile('*.csv');
ReadInFileY = load(fileY)
% go through your code
else
fprintf('back off.')
end
Sorry...missed some lines...
fprintf('Wanna choose files?\n');
prompt = ('y or n ')
str = input(prompt, 's');
if str == 'y'
fprintf('choose x file\n');
[fileX,path] = uigetfile('*.csv');
ReadInFileX = load(fileX)
% go through your code
fprintf('choose y file\n');
[fileY,path] = uigetfile('*.csv');
ReadInFileY = load(fileY)
% go through your code
else
fprintf('back off.')
end
Right below
ReadInFileX = uigetfile();
you can
f = msgbox({'X-Files';'Completed'}); % or something like that.
% To tell the user in a window their fileX are loaded.
Or play with
java.lang.Thread.sleep(duration*1000) % in milisec
From this Q&A.
Thanks for the feedback. I was playing with java.lang.Thread.sleep(duration*1000) % in milisec
I get the following error: No method 'java.lang.Thread.sleep' with matching signature found...
using the below code. I haven't found any docs to say what this means or how to fix it. Any ideas?
fprintf('Wanna choose files?\n');
prompt = ('y or n ')
str = input(prompt, 's');
if str == 'y'
fprintf('choose x file\n');
[fileX,path] = uigetfile('yourExtension');
ReadInFileX = load(fileX)
java.lang.Thread.sleep(duration*3000) % in milisec
%[fileX, path] = uigetfile('yourExtension');
%if isequal(fileX,0)
% disp('User selection for X file cancelled');
%end
% go through your code
fprintf('choose y file\n');
[fileY,path] = uigetfile('*.csv');
ReadInFileY = load(fileY)
java.lang.Thread.sleep(duration*3000) % in milisec
%if isequal(fileY,0)
% disp('User selection for Y file cancelled');
%end
%[fileY, path] = uigetfile('yourExtension');
else
fprintf('back off.')
end
After continued reading of docs, I think I figured it out. Or at least I'm not getting the error anymore. I set duration. Ha....thanks.

Sign in to comment.

Categories

Asked:

on 29 Oct 2020

Commented:

on 7 Nov 2020

Community Treasure Hunt

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

Start Hunting!