How to change specific numbers to 0
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
William
el 16 de Jun. de 2023
Respondida: Daniel
el 17 de Jun. de 2023
So here is my current code:
A = [ 1 2 3 4 5 6 7 8 9];
B = [ 1 2 3 4];
A(~B)=0;
disp(A);
Basically I want A to be equal to [ 1 2 3 4 0 0 0 0 0 ]. But for some reason it won't take ~B, where as it will work when it is just B. Anyone know a solution to this or why this is the case? Thanks in advance!
2 comentarios
Stephen23
el 17 de Jun. de 2023
"But for some reason it won't take ~B, where as it will work when it is just B. "
Compare:
B = [1,2,3,4]
~B
The first is a numeric array, the second is a logical array. Now revise what kind of indexing MATLAB supports:
Respuesta aceptada
Daniel
el 17 de Jun. de 2023
There are two ways you can select elements of an array in MATLAB.
- Pass in an array of valid indices. "Valid" means that they're within the range of indices to the array.
- Pass in an array of logical values, of the same size as the array.
a = (1:10)*2; % Demo array. This has 10 elements, indexed 1 through 10, values 2, 4, 6, ... 20.
% First method
a(1)
a(10)
a(end) % Special case: "end" refers to the last element in the array
a([5 7 2])
% Second method
mod(a,4) == 0 % Notice that this returns a "logical" data type at the output, as will any comparison
a(mod(a,4)==0)
~ is a logical operator, so ~B is an array of logicals. Since it's a logical array, it has to have the same size as A, which it doesn't. Therefore the line of code fails.
One alternative method would be to write:
A(5:end) = 0;
That will select and modify elements 5 through 9 (the last element) of A.
0 comentarios
Más respuestas (1)
John D'Errico
el 16 de Jun. de 2023
Editada: John D'Errico
el 16 de Jun. de 2023
For some reason? Learn to use ismember instead. What you think makes sense does not work in MATLAB. And that means you need to start back with the tutorials, to learn MATLAB syntax. Sorry. Time to start at the beginning.
2 comentarios
Daniel
el 17 de Jun. de 2023
Regarding starting at the beginning, speaking as a MathWorker, you probably have access to some MATLAB fundamentals courses if you go to matlab.mathworks.com through your university account and click on "Online Training". You may find the MATLAB Onramp and/or MATLAB Fundamentals to be helpful.
Ver también
Categorías
Más información sobre Get Started with MATLAB en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!