I have a square matrix of ones and zeroes and I am trying to change all the ones to a user entered number. I am only successfully changing the first value in the matrix.
조회 수: 1 (최근 30일)
이전 댓글 표시
for i = matrix_A(1,:)
if i == 1
matrix_A(i) = user_input
end
end
댓글 수: 0
채택된 답변
KSSV
2021년 11월 16일
편집: KSSV
2021년 11월 16일
A = rand(3) ;
A(A<0.5) = 0 ;
A(A>=0.5) = 1 ;
idx = find(A==1) ;
for i = 1:length(idx)
[r,c] = ind2sub(size(A),idx(i)) ;
fprintf('Enter value for (%d,%d) position\n',r,c)
val = input('Enter value:') ;
A(idx) = val ;
end
If you have a fixed single value:
A = rand(3) ;
A(A<0.5) = 0 ;
A(A>=0.5) = 1 ;
idx = find(A==1) ;
val = input('Enter value:') ;
A(idx) = val ;
댓글 수: 0
추가 답변 (1개)
DGM
2021년 11월 16일
편집: DGM
2021년 11월 16일
You can do this with logical indexing.
For example:
% test array
A = randi([0 1],5,5)
newvalue = 12; % value to substitute
A(A==1) = newvalue
As to why your loop isn't working
for i = matrix_A(1,:) % i is always either 0 or 1
if i == 1 % if it's 1
matrix_A(i) = user_input; % assign a value to matrix_A(1)
end
end
You could instead do something like this
for col = 1:size(matrix_A,2)
if matrix_A(1,col) == 1
matrix_A(1,col) = user_input;
end
end
but as indicated above, it's entirely unnecessary to use loops.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!