I need help with shifting the values

17 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 9 Oct 2017
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]
  3 Comments
Walter Roberson
Walter Roberson on 9 Oct 2017
Maybe, but the array might be a column vector; all we know is it has 3 elements.
Ashlyn Rimsky
Ashlyn Rimsky on 3 Feb 2018
Jan Simon thank you! I am not the writer of this question but I as well could not figure out how to do this and your answer is by far the most simplified / easiest way to do this. Thank you! This is good to know.

Sign in to comment.

More Answers (1)

Joshua Olatunji
Joshua Olatunji on 23 Feb 2021
A more general way for any array is:
% Write a statement to shift the array contents 1 position to the left
sampleReadings = sampleReadings([2:end]);
% Assign the rightmost element with -1
sampleReadings = [sampleReadings(1:end),-1]
  1 Comment
saphir alexandre
saphir alexandre on 30 Jan 2022
thank you so much i was really struggling to understand this question

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!