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.

3 views (last 30 days)
Julian Kerr
Julian Kerr on 16 Nov 2021
Edited: DGM on 16 Nov 2021
for i = matrix_A(1,:)
if i == 1
matrix_A(i) = user_input
end
end

Accepted Answer

KSSV
KSSV on 16 Nov 2021
Edited: KSSV on 16 Nov 2021
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 ;

More Answers (1)

DGM
DGM on 16 Nov 2021
Edited: DGM on 16 Nov 2021
You can do this with logical indexing.
For example:
% test array
A = randi([0 1],5,5)
A = 5×5
1 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1
newvalue = 12; % value to substitute
A(A==1) = newvalue
A = 5×5
12 0 0 0 12 12 12 0 0 0 0 0 12 0 0 0 0 12 0 12 0 0 12 0 12
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.

Community Treasure Hunt

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

Start Hunting!