I am getting this error "Attempted to access a(2); index out of bounds because numel(a)=1. Error in generateShare (line 16) a2 = a(2);" after running the following code

function out = generateShare(a,b)
a1 = a(1);
a2 = a(2);
b1 = b(1);
b2 = b(2);
in = [a
b];
out = zeros(size(in));
randNumber = floor(1.9*rand(1));
if (randNumber == 0)
out = in;
elseif (randNumber == 1)
a(1) = a2;
a(2) = a1;
b(1) = b2;
b(2) = b1;
out = [a
b];
end

Answers (1)

juhi - the error message is telling you that you are trying to access an element of the array a using an index that is invalid. In this case, your a is a 1x1 (scalar) and your code is trying to get the second element of it via a(2) which will not work since a is a scalar and not an array.
When you call the function generateShare, it is expected that the two inputs, a and b, are 2x1 (or 1x2) arrays and not scalars and so you must pass them in as such. For example,
generateShare([1 2], [3 4])
should work.

Asked:

on 15 Oct 2015

Answered:

on 15 Oct 2015

Community Treasure Hunt

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

Start Hunting!