Replacing multiple values at specific indices in a matrix with a single value
    12 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    bsriv
 el 8 de Sept. de 2019
  
Hi,
I have a 91282x1 (d) array with a lot of different values.  I would like to replace certain values (all at multiple indices) with 1 (there is no value of 1 in the original matrix) and the rest with zeros- but in a much more efficient way.   Here's what I have
d(d==7201 | d==7205 | d=7207 | d==7208 | d==7209 | d==7210 | d==7215)=1;
d.(d~=1)=0
I know this is really short but I have to do this for a lot and I'm wondering if there's a more efficient way to make the mask by using zeros and then ID'ing the appropriate indices... or something
Thanks
0 comentarios
Respuesta aceptada
  David Hill
      
      
 el 8 de Sept. de 2019
        values = [7201,7205,7207,7208,7209,7210,7215];
d=sum(d==values,2);
The above should be easier.
2 comentarios
  Adam Danz
    
      
 el 8 de Sept. de 2019
				
      Editada: Adam Danz
    
      
 el 8 de Sept. de 2019
  
			Just be aware that this method requires 'd' to be a column vector and 'values' to be a row vector.  Also, if there are duplicate values in "values" then you will not have just 1s and 0s.  
The ismember() approach avoids both of those potential issues.  
One improvement to this method would be to force the inputs to be the correct shape (row or column). 
d=sum(d(:)==values(:).',2);
Más respuestas (1)
  Adam Danz
    
      
 el 8 de Sept. de 2019
        
      Editada: Adam Danz
    
      
 el 8 de Sept. de 2019
  
      ismember() will return a logical array the same size as 'd'.  If you need ones and zeros rather than true and false, you can convert that to double. 
d0 = ismember(d,[7201 7205 7207 7208 7209 7210 7215]); 
% If you need double rather than logical
d0 = double(ismember(d,[7201 7205 7207 7208 7209 7210 7215]); ); 
Ver también
Categorías
				Más información sobre Logical 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!


