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 view (last 30 days)
Show older comments
for i = matrix_A(1,:)
if i == 1
matrix_A(i) = user_input
end
end
0 Comments
Accepted Answer
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 ;
0 Comments
More Answers (1)
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)
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 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!