Replace for loop values saved as a vector using a condition

I'm trying to find a simple way to change values in a for loop that are 0 into 'NaN'. For example:
r = [1 9 0 0 1 2 5 16] and I want it to print [1 9 NaN NaN 1 2 5 16]
I was trying to for something like this:
for i = 1:size(r) % r is 3 data samples with 100 values with the first 10 used for a baseline
a = r(i,:);
thresh = mean(r(i,1:10))+ 2*std(r(i,1:10));
start= find(a>thresh); %find where the numbers exceed the threshold
if isempty(start) %setting the traces without values above the threshold to zeros
Rresults(i) = start(1); %Saving the first value past the threshold in a vector
start(start(1)<0) = 'NaN'
end
end
I can't get the values to change using the method I have above. Any help or advice would be greatly appreciated.

 Risposta accettata

Use ‘logical indexing’:
r = [1 9 0 0 1 2 5 16];
r(r==0) = NaN
r =
1 9 NaN NaN 1 2 5 16
This implicitly first creates a logical vector that is true for the 0 values, then replaces those values with NaN. See the documentation on Using Logicals in Array Indexing (link) for details.

2 Commenti

That worked! Thank you
My pleasure!
If my Answer helped you solve your problem, please Accept it!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by