How can I replace values in an array with the value in the previous column's value?

10 views (last 30 days)
I'm trying to replace a column's value with the previous column's value. Here's my code:
n = [0 0 0 0] %create a matrix with four elements
%msrd_dist(k) is a new value for each iteration
for k=1:10
n(4)=n(3); %wanting to replace a new value with the previous column's value
n(3)=n(2);
n(2)=n(1);
n(1)=msrd_dist(k);
For example, this is what I want it to do:
fist iteration
msrd_dist = 15
n=[15 0 0 0]
second Iteration
msrd_dist =13
n=[13 15 0 0]
third iteration
msrd_dist = 14
n=[14 13 15 0]
until iteration 10
msrd_dist = 54
n=[54 63 52 40]
I am fairly new to Matlab so, any help or suggestions are welcome.

Accepted Answer

Jos (10584)
Jos (10584) on 8 Feb 2018
Somewhat simpler:
n = zeros(1,4) ; % array of specific length
while (1) % indefinitely, until you hit ctrl-C
msrd_dist = randi(99) ; % new value
n(:) = [msrd_dist n(1:end-1)] ; % shift array, discard last element
disp(n) ; pause(1) ; % for display purposes only
end
  2 Comments
Caleb Lindhorst
Caleb Lindhorst on 9 Feb 2018
Edited: Caleb Lindhorst on 9 Feb 2018
This is exactly what I need but when I try to implement the code but modified it to fit my uses and it says "Dimensions of matrices being concatenated are not consistent.
In this code 'num' changes value everytime depending on the length of my data and 'msrd_dist' is the value for the measured distance from my LIDAR.
num=length(msrd_dist);
for k=1:num
n(:) = [msrd_dist n(1:end-1)];
The error says that the dimensions are not consistent. I found an answer online saying to transpose it, I tried that and it is not working.
I have tried a lot of different attempts and nothing is working;
Jos (10584)
Jos (10584) on 9 Feb 2018
Apparently msrd_dist is not a scalar (single value), as you originally suggested. Can you give a specific example?

Sign in to comment.

More Answers (2)

Star Strider
Star Strider on 7 Feb 2018
Try this:
n(1,:) = [0 0 0 0]; %create a matrix with four elements
L = numel(n);
for k1 = 2:10
msrd_dist = randi(99)
n(k1,:) = [0 n(k1-1,1:end-1)] + [msrd_dist zeros(1,L-1)]
end
I have no idea what ‘msrd_dist’ is or does, other than produce a two-digit integer in each iteration. So I use the randi function to simulate it.
  3 Comments
Star Strider
Star Strider on 7 Feb 2018
With that specification, try this:
n = [0 0 0 0]; % create a matrix with four elements
L = zeros(1,numel(n)-1);
for k1 = 1:10
msrd_dist = randi(99)
n = [0 n(1:end-1)] + [msrd_dist L]
end
Experiment to get the result you want.

Sign in to comment.


Caleb Lindhorst
Caleb Lindhorst on 8 Feb 2018
This is exactly what I would like for it to do.

Community Treasure Hunt

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

Start Hunting!