How to Imorting a text file containig indexes and the coressponding elements of a matrix to matlab?

1 回表示 (過去 30 日間)
want to get a matrix from a text file that contains the corresponding elements and there indexes.

採用された回答

Pavan Sahith
Pavan Sahith 2024 年 6 月 19 日
編集済み: Pavan Sahith 2024 年 6 月 20 日
Hello Himanshu,
I see that you are looking to import a matrix from a text file containing corresponding elements and their indices. Let's create a sample text file and see how to import it into MATLAB.
As I dont have any text file , I am creating sample.txt with some random data
% Create a sample file
data = [1, 1, 5.5; 1, 2, 6.3; 2, 1, 7.8; 2, 2, 8.1];
writematrix(data, 'sample.txt', 'Delimiter', ',');
To import this text file into MATLAB, you can use the 'readmatrix' function:
data = readmatrix('sample.txt');
then you can extract the indices and values, then populate a matrix accordingly by using a simple 'for' loop :
% Extract indices and values
row_idx = data(:, 1);
col_idx = data(:, 2);
values = data(:, 3);
% Determine the size of the matrix
max_row = max(row_idx);
max_col = max(col_idx);
% Initialize the matrix
matrix = zeros(max_row, max_col);
% Populate the matrix
for i = 1:length(values)
matrix(row_idx(i), col_idx(i)) = values(i);
end
% Display the matrix
disp(matrix);
you can refer to following MathWorks documentation to know more about
I hope this helps you complete your task.
  2 件のコメント
HIMANSHU
HIMANSHU 2024 年 6 月 20 日
Hello Pavan!
Thanks for answering
Your code is work fine but the matrix i am getting is too big, so it is showing a message that the matrix is too big(101 gb) for the physical memory.
Is there any way to create a sparse matrix without creating a full matrix.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2024 年 6 月 20 日
移動済み: Walter Roberson 2024 年 6 月 20 日
Use spalloc -- pass in the number of rows, number of columns, and the total number of entries, and get out a sparse matrix that you can then set individual elements using a loop.
Or, just use sparse passing in the row indices, column indices, and corresponding data values: this will construct the entire array in one call.
Just don't sparse() a partial matrix and then loop setting more elements than were previously allocated -- growing a sparse matrix is expensive.
  1 件のコメント
HIMANSHU
HIMANSHU 2024 年 6 月 20 日
移動済み: Walter Roberson 2024 年 6 月 20 日
Thanks Walter for your answer
This is exactly what I was looking for.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by