How can I convert indices into a binary matrix?

2 ビュー (過去 30 日間)
MByk
MByk 2024 年 2 月 18 日
コメント済み: Alexander 2024 年 2 月 18 日
Hello all, I have a txt file that includes list of selected items (there are 10 items in total). I am reading the file using "readmatrix". I want to create a binary (logical) matrix as in the example below but I am getting "The subscript vectors must all be of the same size." message. How can I fix it? Thanks for the help.
1,3,5 -> 1,0,1,0,1,0,0,0,0,0
1,2,3,7 -> 1,1,1,0,0,0,1,0,0,0
1,2,6,7,8 -> 1,1,0,0,0,1,1,1,0,0
1,2,3 -> 1,1,1,0,0,0,0,0,0,0
...
  1 件のコメント
Stephen23
Stephen23 2024 年 2 月 18 日
@MByk: please upload a sample data file by clicking the paperclip button.

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

採用された回答

Dyuman Joshi
Dyuman Joshi 2024 年 2 月 18 日
編集済み: Dyuman Joshi 2024 年 2 月 18 日
ItemSet = readmatrix('Test.txt','NumHeaderLines',0)
ItemSet = 31×7
1 5 9 10 NaN NaN NaN 1 5 9 10 NaN NaN NaN 1 5 8 9 10 NaN NaN 1 5 7 9 10 NaN NaN 3 5 9 10 NaN NaN NaN 3 5 8 9 10 NaN NaN 3 5 7 9 10 NaN NaN 3 4 5 9 10 NaN NaN 3 4 5 8 9 10 NaN 3 4 5 7 9 10 NaN
tic
s = size(ItemSet);
%corresponding row values
row = repelem((1:s(1)).', 1, s(2))
row = 31×7
1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 9 9 9 9 9 9 9 10 10 10 10 10 10 10
%maximum value
m = max(ItemSet, [], 'all');
%subscript values
idx = [row(:) ItemSet(:)];
%check for NaN values
k = isnan(idx(:,2));
out = accumarray(idx(~k,:), 1, [s(1) m])
out = 31×10
1 0 0 0 1 0 0 0 1 1 1 0 0 0 1 0 0 0 1 1 1 0 0 0 1 0 0 1 1 1 1 0 0 0 1 0 1 0 1 1 0 0 1 0 1 0 0 0 1 1 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 0 1 0 1 1 0 0 1 1 1 0 0 0 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 1 0 1 1
toc
Elapsed time is 0.010489 seconds.

その他の回答 (1 件)

Alexander
Alexander 2024 年 2 月 18 日
Maybe something like the following?
fid = fopen('Item.txt');
A = [];
while(~feof(fid))
syLine = fgetl(fid);
dyA = zeros(1,10);
syLine = ['[' syLine ']'];
dyLine = eval(syLine);
dyA(dyLine) = 1;
A = [A; dyA];
end
A
fclose(fid)
  3 件のコメント
MByk
MByk 2024 年 2 月 18 日
Thank you Alexander and Stephen23.
Alexander
Alexander 2024 年 2 月 18 日
Thanks @Stephen23

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by