1
function [ result ] = addprimes( s, e )
    z = s:e;
    result = sum(z(isprime(z)));
end
  1. z= s:e creates a unit-spaced vector z with elements [s,s+1,s+2,...,e]
  2. isprime(z) returns an array with logical 0 or 1 in places depending upon whether it is non-prime or prime.
  3. what happens in z(...)? What is the name of this operation? can anybody explain this?

1 Answers1

3

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.

Zhe
  • 1,804
  • 1
  • 11
  • 10