-1

I have a question based on the below function. How to return a NaN or empty matrix if a condition is false.

Below function actually check if the Anchor ID and Source ID are present and if such a combination exists it goes further inside the loop to check if Anchor Channel and Source Channel exists if it exists then it will calculate "y" and goes on. But what if the Anchor Channel and source Channel does not exist for this condition ? and also consider what if Anchor ID and source ID does not exist !!! If it does not exist then I want it to return to NaN or simply nil.

How to modify this function to my requirements ??

function [rssi_dBm1]= sampletrue(BlinkSetList,AnchorID,SourceID)

for i=1:length(BlinkSetList)
    S=cell2mat(BlinkSetList(i));                                   
    for j=1:length(S)
        if S(j).AnchorID==AnchorID && S(j).SourceID==SourceID       
            if S(j).AnchorChan==0 && S(j).SourceChan==0             
                y=S(j).agc;                                             
                rssi_dB1(i)= -(33+y*(89-33)/(29-1));
            else
                rssi_dB1(i)=NaN;              
            end
        end
    end
end

rssi_dB1(rssi_dB1==0)=[];
rssi_dBm1=sum(rssi_dB1(:))/length(rssi_dB1);
disp([sprintf('The rssi value  with A-Chan 0 and S-Chan 0 is %0.0f',rssi_dBm1)]);

Note: This is just a one part of the conditions, there are still three more combinations for anchor channel and source channel to evaluate.

If the question is still not clear post your doubts and I will try to explain it more precisely.

Your help is highly appreciated . Thanks in advance.

1 Answers1

3

An example of function returning Nan

function ret = retNan( value )
if value == true
   ret = 1;
else
   ret = NaN;  % set returned value to Nan
end

A function that returns an empty matrix

function ret = retEmpty( value )
if value == true
   ret = 1;
else
   ret = [];  % set returned value to an empty matrix
end

EDIT:
Bottom line, whatever the value of variable ret (or in your case, rssi_dBm1) is at the end of the function - this value is returned. So, if ret is empty or NaN the function simply returns an empty/NaN value.
You may set rssi_dBm1 to be an empty matrix at the beginning of the function and only change it if conditions are satisfied. In that case if all conditions fails the function will return the default value - an empty matrix.

PS,
1. It is best not to use i and j as variable names in Matlab.
2. You can use mean instead of sum()/length().
3. instead of disp( sprintf(...) ) you may use fprintf(1, ... )

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371