How can I replace values in an array with the value in the previous column's value?
10 views (last 30 days)
Show older comments
Caleb Lindhorst
on 7 Feb 2018
Commented: Jos (10584)
on 9 Feb 2018
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.
0 Comments
Accepted Answer
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
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?
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
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.
See Also
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!