Function returns 'NaN' when running it in a loop after second iteration
17 次查看(过去 30 天)
显示 更早的评论
Hello~ I have the following code with 'RI' matrix that is interpolated in 'RefIndex' function in which, if we input an argument 'wave' into 'RefIndex' function, the for-loop within the function will return the corresponding refractive index from 'ri2' matrix.
Here, I want to repeat this 'RefIndex' function using a for-loop for a given set of 'wave' argument from within 'ri2' matrix of first column. However, when I run the for-loop for the 'RefIndex' function to be repeated, it returns a correct value only in the first iteration but returns 'NaN' for second iteration unti the last iteraction.
Can someone please help me figure it out where I did wrong here? I had checked many times but couldn't find one where the mistake is.
global RI; global ri2;
RI = [0.25, 1.6;
0.26, 1.7;
0.27, 2.1;
0.28, 2.8;
0.29, 4.2];
% When I run this loop, it returns the value of RefIndex function only in the first interation but returns 'NaN' in second iteration until the last iteration.
for k = 5:10
ans_n = RefIndex(ri2(k,1))
end
% This is the RefIndex function that, when we input an argument 'wave', it will return a value from second column of 'ri2'
function N = RefIndex(wave)
global RI; global ri2;
RI(:,1)=RI(:,1)*1000;
inter=(250:1:290)';
temp2=interp1(RI(:,1),RI(:,2),inter);
ri2=horzcat(inter,temp2);
row=height(ri2)
for number 1:row
if ri2(number,1) - wave == 0
N = ri2(number,2);
end
end
end
0 个评论
回答(1 个)
Star Strider
2021-3-11
Please promise to never again use global variables!
That aside, and since ‘ri2’ is nowhere to be found, I can’t run your code.
Taking a wild guess as to where the NaN values originate (since I don’t see any divisions anywhere), change the function to:
function N = RefIndex(wave,RI,ri2)
RI(:,1)=RI(:,1)*1000;
inter=(250:1:290)';
temp2=interp1(RI(:,1),RI(:,2),inter, 'linear','extrap');
ri2=horzcat(inter,temp2);
row=height(ri2)
for number = 1:row
if ri2(number,1) - wave == 0
N = ri2(number,2);
end
end
end
passing ‘RI’ and ‘ri2’ as parameters, and allowing interp1 to extrapolate, since I suspect that is where the NaN values originate.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 NaNs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!