How can I replace values in an array with the value in the previous column's value?
Afficher commentaires plus anciens
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.
Réponse acceptée
Plus de réponses (2)
Star Strider
le 7 Fév 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 commentaires
Caleb Lindhorst
le 7 Fév 2018
Star Strider
le 7 Fév 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)
le 8 Fév 2018
Why the +?
Caleb Lindhorst
le 8 Fév 2018
0 votes
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!