How does MATLAB handle vector logic?
Afficher commentaires plus anciens
If I have large vectors to consider and a scalar value of interest, such as:
vec1 = randi([0 1], 1, 1000000) % zeros and ones
vec2 = randi([1 1000000],1,1000000) % random integers
val = 50; % value I want to test for
Would this
vec1 & vec2 == val % conditional statement 1
be faster than this?
vec2 == val & vec1 % conditional statement 2
Reason: I learned in C class that in an AND operation, if there exists a single condition that is false, no further testing is done and the output is immediately placed as false. What I am wondering is if MATLAB will do the same in vector notation for each element in the vectors being compared (e.g. conditional statement 1 will have less logical operations than conditional statement 2)?
=====================================
EDIT: I made the following script, thinking that I was correct in my inference.
profile on
vec1 = randi([0 1], 1, 1000000); % zeros and ones
vec2 = randi([1 1000000],1,1000000); % random integers
val = 50; % value I want to test for
for k = 1:1000
tic
vec1 & vec2 == val; % conditional statement 1
toc
tic
vec2 == val & vec1; % conditional statement 2
toc
end
profsave
profile off
Sadly, the results are the opposite of my inference. Conditional statement 1 runs in 2.734s while conditional statement 2 runs in only 1.813s. Why is this the case?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Entering Commands dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!