save and read a string matrix in a .txt file
11 views (last 30 days)
Show older comments
hi,
i have problems with saving and reading a string matrix in a .txt file. My idea was to save username and password to be able to have the same accounts when the program is interrupted, i tried with readmatrix/writematrix, but read matrix doesn't work. I also have other file in my program with numbers and with the same system read/write matrix they work. I also tried using importdata but i can't get it work. I would really appriciate any help if it's possible, thanks you!
1 Comment
Accepted Answer
Avni Agrawal
on 8 May 2024
Hi Marco,
i understand that you are trying to save and read a string matrix in a .txt file. If you have a text file containing a matrix of strings (usernames and passwords), and you want to read this matrix into MATLAB, you can use the `textscan` function for a high degree of flexibility, or `readtable` for a more straightforward approach.
Below are examples for both methods.
Assuming you have a text file named `stringMatrix.txt` with the following content:
user1,pass1
user2,pass2
user3,pass3
1. Using `textscan`
% Open the file for reading
fileID = fopen('stringMatrix.txt', 'r');
% Read the data, assuming comma-separated values
data = textscan(fileID, '%s%s', 'Delimiter', ',');
% Close the file
fclose(fileID);
% Extract the columns to separate cell arrays
usernames = data{1};
passwords = data{2};
% Display the read data
disp(usernames);
disp(passwords);
This approach reads the strings into cell arrays, where `usernames` and `passwords` will each be a cell array containing the respective column from the file.
2. Using `readtable`
% Read the file into a table, assuming comma-separated values
T = readtable('stringMatrix.txt', 'Format', '%s%s', 'ReadVariableNames', false);
% Convert table columns to cell arrays (if needed)
usernames = table2cell(T(:, 1));
passwords = table2cell(T(:, 2));
% Display the read data
disp(usernames);
disp(passwords);
This method reads the data into a table and then converts the relevant columns into cell arrays. If working directly with a table is suitable for your application, you can skip the conversion to cell arrays and access the data using `T.Var1` and `T.Var2`, or assign variable names during the `readtable` call to access them by these names.
Both methods allow you to read a matrix of strings from a text file into MATLAB, and the choice between them can depend on your specific needs and the complexity of the data structure you're working with.
I hope this helps.
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!