user3752566
user3752566

Reputation: 105

How to calculate GCD in MATLAB (variable array)?

I have problem in calculating GCD. Usually GCD in MATLAB uses two variables (ex: a=19, b=88 and gcd(a,b)). But I have one variable array K = [1 1 1 1 2 1 3 2], and for this K, I want to calculate GCD.
How to calculate greatest common divisor of K ?

Upvotes: 1

Views: 1380

Answers (2)

logan rakai
logan rakai

Reputation: 2557

Because gcd(gcd(a,b),c) is the same as gcd(a,b,c) you can iterate through K and get the gcd of the array.

g = K(1)
for i=2:numel(K)
    g = gcd(g,K(i))
end
fprintf('The gcd is %i\n', g)

Upvotes: 1

user2940296
user2940296

Reputation: 153

Specify the elements of array as elements of a symbolic vector.

For your problem-

K = sym([1, 1, 1, 1, 2, 1, 3, 2])
gcd(K)

Upvotes: 1

Related Questions