save and read a string matrix in a .txt file

조회 수: 25 (최근 30일)
marco
marco 2024년 5월 8일
댓글: marco 2024년 5월 8일
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
Mann Baidi
Mann Baidi 2024년 5월 8일
Hi,
It would be great if you can share your text file.

댓글을 달려면 로그인하십시오.

채택된 답변

Avni Agrawal
Avni Agrawal 2024년 5월 8일
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);
{'user1'} {'user2'} {'user3'}
disp(passwords);
{'pass1'} {'pass2'} {'pass3'}
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by