MATLAB: I need help with shifting the values

shifting values

function sampleReadings = ShiftValues(sampleReadings)
% sampleReadings: Array containing 3 elements
% Write three statements to shift the sampleReadings array contents 1 position to the left
% Note: The rightmost element should be -1
sampleReadings = ShiftValues(1:3)
end

Best Answer

Tricky.
The following could probably be written a bit more compactly; it is for the general case where the number of elements in the array is not necessarily prime.
In the case where the number of elements in the array is prime, like you are given, then a second of thought shows that exactly one dimension can be the non-singular dimension, and figuring out which dimension that is would allow some shortcuts to be made in the code.
For example if the number of elements in the array had been given as 4 instead of as 3, then we might be dealing with the case of an array that is 1 x 2 x 1 x 1 x 2, which is obviously going to be a different case than 1 x 4.
idx = repmat({':'}, 1, ndims(sampleReadings));
idx{2} = 1:size(sampleReadings,2)-1;
idx2 = idx;
idx2{2} = idx2{2} + 1;
temp = sampleReadings;
temp(idx{:}) = temp(idx2{:});
idx{2} = size(sampleReadings,2);
temp(idx{:}) = -1;
sampleReadings = temp;
Anyhow, notice that the result for, say, [5; 13; 9] is [-1; -1; -1] . This is correct according to the instructions: all of the rows are shifted left one position, which leaves them empty, and then the rightmost element in each row is to become -1, just the same way that for [5 13 9], the rows are all shifted left one position, giving [13 9], and then the rightmost (vacated) entry in each row is to become -1, giving a result of [13 9 -1]