I need help with shifting the values

18 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by