I need help with shifting the values
41 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Blair Hall
am 9 Okt. 2017
Kommentiert: saphir alexandre
am 30 Jan. 2022
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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 9 Okt. 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 Kommentare
Walter Roberson
am 9 Okt. 2017
Maybe, but the array might be a column vector; all we know is it has 3 elements.
Ashlyn Rimsky
am 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.
Weitere Antworten (1)
Joshua Olatunji
am 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 Kommentar
saphir alexandre
am 30 Jan. 2022
thank you so much i was really struggling to understand this question
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!