The error you're encountering is due to MATLAB interpreting “mydata.txt” and “mydata2.txt” as variables rather than string literals. In MATLAB, to pass file names as arguments to a function, you must use string literals or character arrays. To resolve this issue you can try below given methods:
You can wrap your file names with the “string” function, which is available in MATLAB R2016b and later. This allows you to use double quotes for strings, you can directly use double quotes without needing the string function.
And update the function for the same. Below is the updated code for the same:
function PS5_4(x, y)
% Convert string objects to character arrays if necessary
if isstring(x)
x = char(x);
end
if isstring(y)
y = char(y);
end
% Check if the file exists
if isequal(exist(x, 'file'), 2)
disp('Program will perform some operation, please wait...')
disp('...')
data = dlmread(x); % Read data from the file
data_tp = data'; % Transpose the matrix
disp('Transposed matrix = ')
disp(' ')
disp(data_tp)
dlmwrite(y, data_tp, ' '); % Save transposed matrix to file
else
warningMessage = sprintf('Warning: file %s does not exist. Please try to type a different file name using format ''filename.txt''\n\nProgram will check if file mydata.txt exists; if not, a default matrix will be created:\n1 2 3 4\n5 6 7 8\n9 10 11 12', x);
uiwait(msgbox(warningMessage));
% Check if the default file exists
if isequal(exist('mydata.txt', 'file'), 2)
disp('File mydata.txt exists')
else
disp('File mydata.txt does not exist, Program will create a default matrix and save it')
D = [1 2 3 4; 5 6 7 8; 9 10 11 12]; % Create a default matrix
disp('Default matrix created = ')
disp(' ')
disp(D)
dlmwrite('mydata.txt', D, ' '); % Save the default matrix
D = D'; % Transpose the matrix
disp('Transposed matrix = ')
disp(' ')
disp(D)
dlmwrite(y, D, ' '); % Save transposed matrix with user-specified name
end
end
end
Output for the updated code is given below:
Hope that Helps!