making column of zero matrix equal to one based on another matrix

조회 수: 1 (최근 30일)
Sukuchha
Sukuchha 2014년 2월 25일
댓글: Image Analyst 2014년 2월 26일
Hi ,
I have a zero matrix (A) of size mxn where m in number of observation and n number of feature. I have another non zero matrix (B) of size (mx1) where numbers respresent column in matrix A which should be replaced by one.
How to do this ?

채택된 답변

Jos (10584)
Jos (10584) 2014년 2월 25일
Perhaps you want to set in a row K of A, the entry in column B(k) to one?
%data
A = zeros(3,3)
B = [3; 1; 2] % column index
% engine
R = 1:numel(B) % row index
idx = sub2ind(size(A), R, B) % convert to linear indices into A
A(idx) = 1
Note that the statement A(R,B) = 1 does not do what you might think it should do.
  댓글 수: 5
Jos (10584)
Jos (10584) 2014년 2월 26일
@Image Analyst My apologies, I should have tested the code properly, rather than write it down theoretically.
@Sukuchha, I am glad you solved this issue yourself.
Image Analyst
Image Analyst 2014년 2월 26일
No problem - I sometimes post untested code off the top of my head also, and mistakes do happen. Actually I'm kind of impressed that you (1) actually figured out what he meant, and (2) thought up that somewhat cryptic solution off the top of your head.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 2월 25일
Did you try
A(:, B) = 1;
  댓글 수: 3
Paul
Paul 2014년 2월 25일
편집: Paul 2014년 2월 25일
Well, that is what you said you want. Since all three the column indices are present in B, all values of A are set to 1.
Image Analyst
Image Analyst 2014년 2월 25일
편집: Image Analyst 2014년 2월 25일
I agree with Paul. You said any column number of A that shows up in B should have that entire column of A set to 1. For example:
A = randi(9, 5, 8) % Random integers
B = [1,3,7]; % Set columns 1, 3, and 7 to all 1's.
A(:, B) = 1

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by