Make spceficic array values zero.
    3 views (last 30 days)
  
       Show older comments
    
    Santos García Rosado
 on 18 Mar 2021
  
    
    
    
    
    Commented: Santos García Rosado
 on 22 Mar 2021
            Hi Mathworks community!
I'm having trouble trying to make some of my array values zero. This array corresponds to my Input: 
Input = [-1 0 -1 0 0 NaN NaN NaN NaN  -1 0 -1 -1 -1 0 NaN NaN NaN 0 0 -1 0 -1 NaN NaN NaN]
I'd like to make everything inside the array zero, but the last -1 before every NaN series. This should be the expected Output:
Output = [0 0 -1 0 0 0 0 0 0  0 0 0 0 -1 0 0 0 0  0 0 0 0 -1 0 0 0]
Could someone please help me out?
Thank you,
Santos
0 Comments
Accepted Answer
  David Hill
      
      
 on 18 Mar 2021
        a=find(diff(isnan(Input))==1);
b=find(Input==-1);
Output=zeros(size(Input));
for k=a
    Output(b(find(b<=k,1,'last')))=-1;
end
3 Comments
  David Hill
      
      
 on 18 Mar 2021
				You could do something like:
Input = [-1 0 -1 0 0 NaN NaN NaN NaN  -1 0 -1 -1 -1 0 NaN NaN NaN 0 0 -1 0 -1 NaN NaN NaN];
Output=zeros(size(Input));
idx=[];
for k=1:length(Input)
    if Input(k)==-1
        Output(k)=-1;
        idx=[idx,k];
    end
    if isnan(Input(k))
        Output(idx(1:end-1))=0;
        idx=[];
    end
end
More Answers (0)
See Also
Categories
				Find more on Resizing and Reshaping Matrices 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!