2

There are matices A(n,1), B(n,1) and the following condition inside a loop

for i=1:m
   if ( A(i, 1) > error )
      B(i,1) = 0;
   else
      B(i,1) = exp (-A(i,1) / 100)
   end
end

How to rewrite this condition without using any loop? Is it possible something like that

 if ( A(:, 1) > error )
      B(:,1) = 0;
   else
      B(:,1) = exp (-A(:,1) / 100)
 end

2 Answers 2

7

Use logical indexing:

idxs = (A > error);
B( idxs) = 0;
B(~idxs) = exp(-A(~idxs) / 100);
Sign up to request clarification or add additional context in comments.

Comments

2

You were close with your suggestion. The key is to form a "logical index."

i = A(:,1) > error;

B(i,:) = 0;
B(~i,:) = exp (-A(:,1) / 100);

Since your matrices A and B are vectors (one-dimensional matrices), the (:,1) and (i,:) aren't necessary in this case but as they were in your initial formulation, I left them in. If you were using multi-dimensional matrices instead (m * n) you could form an (m * n) logical index rather than (m * 1) by doing i = A > error; instead of i = A(:,1) > error;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.