How can I replace values in an array with the value in the previous column's value?
Show older comments
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
More Answers (2)
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
Caleb Lindhorst
on 7 Feb 2018
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.
Jos (10584)
on 8 Feb 2018
Why the +?
Caleb Lindhorst
on 8 Feb 2018
0 votes
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!