Output arguments not getting assigned?
Show older comments
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
Accepted Answer
More Answers (1)
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));
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!