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.

 채택된 답변

Star Strider
Star Strider 2018년 3월 24일
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

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2018년 3월 24일

댓글:

2018년 3월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by