How do I use if elseif to find indices of elements that meet a statement and assign NaN to elements that don't?

1 次查看(过去 30 天)
Hi All,
I have a 3D matrix (a2).
I want to find the index of elements in a2 <= -0.1 in the first dimension for all trials (trl) and experiments (exp). Some of my trials (trl) don't have values <=-0.1, and for these I would like to assign them with NaN.
I've had a go at writing code, but my if elseif statement is completely off. Can someone please give me some pointers on what I should do.
Many thanks
onsetT=zeros(trl,anim); %preallocate
for exp = 1:12 %experiments
for trl=1:50 %trials
if a2(:,trl,exp)<=-0.1 %if there are elements <=0.1
[row] = find(a2(:,trl,exp)<=-0.1,1); %find index of these elements
onsetT(trl,exp)=lfpTime(row); %use index to locate onset time
elseif a2(:,trl,exp)>=0 %if elements >0 i.e. positive
a2(:,trl,exp)=NaN; %assign them with NaN
onsetT(trl,exp)=a2(:,trl,exp); %assign onset time for these trials NaN
end
end
end

回答(1 个)

KSSV
KSSV 2021-6-16
If a is your matrix, to replace the values which are less than -0.1 just use:
idx = a < -0.1 ;
a(idx) = NaN ;
  1 个评论
NA
NA 2021-6-16
Thanks for this. The issue I am facing now, is that I get an error message at the point were the for loop comes across a trial where all the values are NaN: "Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-0."
I tried to overcome this by adding the following line of code but was not successful:
if isnan(a2)
onsetT(trl,exp)=NaN;
else
What I'm trying to do is assign NaN in the matrix 'onsetT' (50x12) when all elements in the trial are NaN.
To put things into prespective my code looks like this:
onsetT=zeros(trl,exp);
idx=a2>0;
a2(idx)=NaN;
for exp =1:12
for trl=1:50
if isnan(a2)
onsetT(trl,exp)=NaN;
else
[row] = find(a2(:,trl,exp)<=-0.1,1);
onsetT(trl,exp)=lfpTime(row);
end
end
end
Your help is appreciated. Thanks

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by