Converting the format Row Column Value into matrix ?

Hi everyone. The question as the title says is that i have an input text file which is in the format row-number column-number value and it has to be converted into a matrix
for example if the test.txt is
1 2 5
1 3 6
2 1 8
2 5 1
3 1 4
3 3 2
this will convert to
0 5 6 0 0
8 0 0 0 1
4 0 2 0 0
I was looking through the matrix indexing but i am very confused here. It would be great if someone could help me out here! Thanks!
p.s: Also note that there will be no overrides for any value in the matrix
edit: fixed the typo in the sample output

2 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 13 日
How the result is related to your data?
rya11111
rya11111 2014 年 8 月 13 日
編集済み: rya11111 2014 年 8 月 13 日
Well the first number of the text file is the row number
the second number in the line is the column number
and the last the value of the corresponding row and column
any value not specified is considered as 0 and the maximum number of columns in the matrix is the highest column number of some row

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

回答 (4 件)

Geoff Hayes
Geoff Hayes 2014 年 8 月 13 日

1 投票

The following uses a for loop but that should be fine for this problem:
% load the data
A = importdata('test.txt');
% use max to determine the row and column dimension of the output matrix
dims = max(A);
% size the output matrix
mtx = zeros(dims(1),dims(2));
% iterate over each row of A and assign to the appropriate entry in mtx
for k=1:size(A,1)
mtx(A(k,1),A(k,2)) = A(k,3);
end
The answer, given your data, is
mtx =
0 5 6 0 0
8 0 0 0 1
4 0 2 0 0
Almost the same as yours except for the 2 replaces your 3.

1 件のコメント

rya11111
rya11111 2014 年 8 月 13 日
Sorry for the typo :D
I will check this soon and let you know the outcome! thanks a lot!

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

Matt J
Matt J 2014 年 8 月 13 日
編集済み: Matt J 2014 年 8 月 13 日

1 投票

S = spconvert(load('test.txt','-ascii'));

2 件のコメント

Matt J
Matt J 2014 年 8 月 13 日
編集済み: Matt J 2014 年 8 月 13 日
You can then convert the matrix to full form if desired,
S=full(S);
but normally the original sparse form is what you want.
rya11111
rya11111 2014 年 8 月 13 日
Thank you so much for taking time to help out!

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

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 13 日

0 投票

A=[1 2 5
1 3 6
2 1 8
2 5 1
3 1 4
3 3 2]
n=max(A(:,1))
m=max(A(:,2))
out=zeros(n,m)
out(sub2ind([n m],A(:,1),A(:,2)))=A(:,3)

1 件のコメント

rya11111
rya11111 2014 年 8 月 13 日
Thank you so much for taking time to help out!

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

Andrei Bobrov
Andrei Bobrov 2014 年 8 月 13 日

0 投票

A = [1 2 5
1 3 6
2 1 8
2 5 1
3 1 4
3 3 2];
out = accumarray(A(:,1:2),A(:,3))

1 件のコメント

rya11111
rya11111 2014 年 8 月 13 日
Thank you so much for taking time to help out!

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

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

質問済み:

2014 年 8 月 13 日

コメント済み:

2014 年 8 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by