MATLAB: Splitting into function files

function

clear
clc
fid = fopen('hangman.txt','r');
if fid < 0, error('Cannot open file'); end
data = textscan(fid,'%s');
data = data{1};
fclose(fid);
index = ceil(rand * numel(data));
word = data{index};
masked = word;
masked(~isspace(masked)) = '*';
complete = 0;
wrong=0;
while complete == 0
clc;
fprintf('Word : %s\n',masked);
letter = char(input('Guess a letter : ','s'));
stat = findstr(word,letter);
if ~isempty(stat)
masked(stat) = letter;
elseif ~isequal(word,letter)
wrong=wrong+1;
end
if isempty(findstr(masked,'*'))
complete = 1;
fail=0;
end
if wrong==6
complete=1;
fail=1;
end
end
if fail==0
clc; fprintf('You win, the word is : %s\n',masked);
elseif fail==1
disp('You lose')
end
My Professor wants me to split this into multiple function files, I'm not entirely sure how he wants me to accomplish that.

Best Answer

Just call the function's name.
I will give U first sample code :)
Replace code below :
fid = fopen('hangman.txt','r');
if fid < 0, error('Cannot open file'); end
data = textscan(fid,'%s');
data = data{1};
fclose(fid);
with :
filename = 'Hangman.txt';
data = load_data(filename);
Now, create a m-file then type this code :
function data = load_data(filename)
fid = fopen(filename,'r');
if fid < 0,
error('Cannot open file');
end
data = textscan(fid,'%s');
data = data{1};
fclose(fid);
Save the code above with filename : 'load_data.m'.
And try to run your code modified now.
Related Question