Effacer les filtres
Effacer les filtres

Fill a zeros matrix with another matrix until it is full

5 vues (au cours des 30 derniers jours)
Davidra Fantarina ANDRIAMISAINA
Commenté : Sumara le 14 Juin 2019
I want to fill the array essai with the value in the array key but my code return zeros
k= 1:length(key);
yr=reshape(y.',1,[]);
essai=zeros(1,length(yr));
essai=uint8(essai);
for n= 1:length(essai)
if k <length(key)
essai(n)=essai(n)+key(k)
else if k== length(key)
essai(n)=essai(n)+key(k);
k=1;
end
end
end
  2 commentaires
Stephen23
Stephen23 le 5 Fév 2018
Modifié(e) : Stephen23 le 5 Fév 2018
@Davidra Fantarina ANDRIAMISAINA: your code is very badly aligned. Badly aligned code is how beginners hide simple bugs and logical errors in their code. You should use the default alignment of the MATLAB editor: select the code and press ctrl+i.
Sumara
Sumara le 14 Juin 2019
THANK YOU! I've wanted to do this for when my code became misaligned but didn't know there was a command for it and fixing manually is so tedious !!!

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 5 Fév 2018
Modifié(e) : Stephen23 le 5 Fév 2018
MATLAB is not an ugly low-level language like C++ and does not need loops to solve all tasks:
idx = 1+mod(0:numel(y)-1,numel(key));
essai = uint8(key(idx));
And tested on some random data:
>> y = 0:9;
>> key = 2:2:8;
>> idx = 1+mod(0:numel(y)-1,numel(key));
>> essai = uint8(key(idx))
essai =
2 4 6 8 2 4 6 8 2 4
  3 commentaires
Davidra Fantarina ANDRIAMISAINA
Thanks, it works but can you explain this idx thing please
Stephen23
Stephen23 le 5 Fév 2018
Modifié(e) : Stephen23 le 5 Fév 2018
"but can you explain this idx thing please"
idx is a vector of indices. Lets look at my example data:
>> y = 0:9 % a vector with ten elements.
y =
0 1 2 3 4 5 6 7 8 9
>> key = 2:2:8 % a vector with four elements.
key =
2 4 6 8
>> idx = 1+mod(0:numel(y)-1,numel(key)) % index vector
idx =
1 2 3 4 1 2 3 4 1 2
>> key(idx) % use the indices
ans =
2 4 6 8 2 4 6 8 2 4
You can see how the idx values are 1 to 4 repeated up until the vector has the same number of indices as y has elements: these indices determine which elements of key will get selected: so the output vector is equivalent to
[key(1),key(2),key(3),key(4),key(1),key(2),key(3),...]

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Workspace Variables and MAT-Files dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by