Home > Net >  What is a Mat-lab function for « If-in »?
What is a Mat-lab function for « If-in »?

Time:12-28

Problem statement: Provide a function that does the following: c1) two vectors D1 and D2 have 7 elements each, then form the division between the corresponding components of each vector and assign the result to a vector name D3, placing a statement that avoids division by zero (i.e., does not divide if element to denominator is null);

The idea of the problem, is to set an error message whenever one of the elements of vector D2 is equal to 0.

My attempt:

D1 = [d1 d2 d3 d4 d5 d6 d7]
D2= [d21 d22 d23 d24 d25 d26 d27]
for i= 1:length(D1)
if 0 in D2
fprintf(‘error: division by 0/n’)
else
D3=D1./D2 
end

I don’t know if the “if-in” structure exists in Matlab. If it doesn’t, what could be an equivalent?

Thanks in advance!!!

CodePudding user response:

One way to avoid any division by zero is to modify D2 by replacing any 0 with nan. Divisions by nan produce nan, so it's easy to tell which division would have caused a problem by simply inspecting the resulting vector D3. Moreover, almost all Matlab's functions are able to handle nans nicely (i.e. without crashing) or can be instructed to do so by setting some option.

What I've just described can be accomplished by using logical indexing, as follows:

% Definition of D1 and D2
D1 = [d1 d2 d3 d4 d5 d6 d7]
D2 = [d21 d22 d23 d24 d25 d26 d27]

% Replace 0s with NaNs
D2(D2==0) = nan;

% Perform the divisions at once
D3 = D1./D2 ;

For more details on logical indexing, look at the relevant section here.

As the OP requests a function that does the job, here's a possible implementation:

function D3 = vector_divide(D1, D2)
   % Verify that vectors are numeric
   % and have the same dimensions
   if isnumeric(D1) & isnumeric(D2) &...
      (size(D1,1) == size(D2,1)) &...
      (size(D1,2) == size(D2,2))

      % replace 0s with NaNs
      D2(D2==0) = nan;

      % Perform the divisions at once
      D3 = D1./D2 ;
   else
      disp('D1 and D2 should both be numeric and have the same size!');
      D3 = [];
end

Error handling in case of non-numeric arrays or size mismatch might vary depending on project requirements, if any. For instance, I could have used error (instead of disp) to display a message and terminate the program.

  • Related