How to shift certain arrays in a matrix downward

4 vues (au cours des 30 derniers jours)
SMA
SMA le 9 Fév 2016
Commenté : SMA le 9 Fév 2016
I have a large matrix where data for each month of 100 years is stored for 12 variables. Some of the variables have data starting from later date. How can a shift those variables down. For example I have a matrix;
1 4 6 9 0 2
3 6 8 8 2 5
2 5 6 8 9 0
3 5 7 9 2 1
And I'd like the output to be (with NaNs replacing the empty places);
1 4 N N N 2
3 6 6 N N 5
2 5 8 9 0 0
3 5 6 8 2 1
Provided I have stored in a different matrix what the lag would be, in this case say lag=[0, 0, 1, 2, 2, 0].

Réponse acceptée

Jos (10584)
Jos (10584) le 9 Fév 2016
This is a fast and easy-to-read solution:
M = [1 4 6 9 0 2
3 6 8 8 2 5
2 5 6 8 9 0
3 5 7 9 2 1] % matrix
S = [0 0 1 2 2 0] % shift for each column
M2 = nan(size(M)) ; % pre-allocation for speed
for k=1:size(M,2) % loop over columns
M2(1+S(k):end, k) = M(1:end-S(k), k) ; % copy column k with a shift
end
disp(M2)
  1 commentaire
SMA
SMA le 9 Fév 2016
Great, I was doing something similar but messed up somewhere. It works with minor modification for my data.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by