How can I convert indices into a binary matrix?
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
Alexander
2024년 2월 18일
1 개 추천
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
"Maybe something like the following?"
But preferably without the evil EVAL. Why do you need it? (hint: you don't)
There are various ways to avoid ugly, evil, inefficient EVAL is this situation, here is just one:
out = nan(0,10);
fid = fopen('Item.txt');
idr = 1;
while ~feof(fid)
idr = idr+1;
idc = [fscanf(fid,'%f');fscanf(fid,',%f')];
out(idr,idc) = 1;
end
fclose(fid);
out
MB
2024년 2월 18일
Alexander
2024년 2월 18일
Thanks @Stephen23
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!