I need help with shifting the values

조회 수: 19 (최근 30일)
Blair Hall
Blair Hall 2017년 10월 9일
댓글: saphir alexandre 2022년 1월 30일
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

채택된 답변

Walter Roberson
Walter Roberson 2017년 10월 9일
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
Walter Roberson
Walter Roberson 2017년 10월 9일
Maybe, but the array might be a column vector; all we know is it has 3 elements.
Ashlyn Rimsky
Ashlyn Rimsky 2018년 2월 3일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Joshua Olatunji
Joshua Olatunji 2021년 2월 23일
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
saphir alexandre
saphir alexandre 2022년 1월 30일
thank you so much i was really struggling to understand this question

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by