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
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
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 个评论

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 Exchange 中查找有关 Loops 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