How to replace every value with the index of the value to the left of it

5 vues (au cours des 30 derniers jours)
sunny blue
sunny blue le 10 Oct 2021
Commenté : sunny blue le 10 Oct 2021
This way the left most column is 0. I initially tried using a while loop but with a really big matrix, it takes way too long. so if I had a matrix
x= [ 2 3 4 5 6 ;
8 9 10 11 12 ]
the matrix i would want is
[ 0 1 3 5 7 9;
0 2 4 6 8 10 ]
I'm kind of at a crossroads here.

Réponses (1)

DGM
DGM le 10 Oct 2021
There's this:
x = [ 2 3 4 5 6 ; 8 9 10 11 12 ]
x = 2×5
2 3 4 5 6 8 9 10 11 12
idx = reshape(1:numel(x),size(x));
out = [zeros(size(x,1),1) idx(:,1:end-1)]
out = 2×5
0 1 3 5 7 0 2 4 6 8
  4 commentaires
Jan
Jan le 10 Oct 2021
The output needs to have one column more than the input. Maybe this matchs the needs:
out = reshape([0, 0, 1:numel(x)], 2, []);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by