Reputation: 27
function [ result ] = addprimes( s, e )
z = s:e;
result = sum(z(isprime(z)));
end
z= s:e
creates a unit-spaced vector z
with elements [s,s+1,s+2,...,e]
isprime(z)
returns an array with logical 0
or 1
in places depending upon whether it is non-prime or prime.z(...)
? What is the name of this operation? can anybody explain this?Upvotes: 1
Views: 42
Reputation: 2123
This is called logical indexing. An example with some numbers:
>> x = [1 2 3 4 5 6];
>> isprime(x)
ans =
1×6 logical array
0 1 1 0 1 0
>> x(isprime(x))
ans =
2 3 5
>> sum(x(isprime(x)))
ans =
10
For more details, look at Logical Indexing – Multiple Conditions and "Logical Indexing" of Matrix Indexing in MATLAB.
Upvotes: 3