Output arguments not getting assigned?

I keep getting the error Output argument "prime2" (and maybe others) not assigned during call to "sum_of_primes". Can someone explain why?
% This function takes an even integer greater than 2
% and expresses it as the sum of two prime integers
function [prime1, prime2] = sum_of_primes (num)
%%If input is an even integer greater than 2
if (mod(num,2) == 0) && (num > 2)
%%Initializing vector x to numbers from 1 to num
% any non-prime number is set to 0
for n = 1:num
if (isprime(n) == true)
x(n) = n;
end
end
%%Initializing vector z as array x without the zeros
% z will then be a vector of prime numbers
z = (x(x~=0))';
z = z<num;
%%Doing things and stuff
for n = 1:size(z)
prime1 = z(n);
if (isprime(num-prime1) == true)
prime2 = num-prime1;
break;
end
end
else
disp('Please enter an integer greater than 2.')
end
end

 採用された回答

MJE
MJE 2017 年 2 月 21 日

0 投票

I fixed it. z = z<num; was messing up the initialization of vector z. I didn't need this line anyways.

その他の回答 (1 件)

Jan
Jan 2017 年 2 月 21 日
編集済み: Jan 2017 年 2 月 21 日

0 投票

for n = 1:size(z)
This will not do, what you expect, because size replies a vector. Better:
for n = 1:numel(z)
The line z = z<num let z be a logical vector. Most likely you mean:
z = z(z < num);
A simplification for the first loop:
v = 1:num;
x = v(isprime(v));

1 件のコメント

MJE
MJE 2017 年 2 月 21 日
I'd found a workaround for that by making the vector z a column vector so that size(z) technically returned the number of elements...but I'll revise it just so that's a little clearer. But, the same error occurs.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

MJE
2017 年 2 月 21 日

回答済み:

MJE
2017 年 2 月 21 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by