mathuser001
mathuser001

Reputation: 27

parenthesis outside a array in matlab

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?

Upvotes: 1

Views: 42

Answers (1)

Zhe
Zhe

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

Related Questions