Borrar filtros
Borrar filtros

Fill a zeros matrix with another matrix until it is full

5 visualizaciones (últimos 30 días)
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 comentarios
Stephen23
Stephen23 el 5 de Feb. de 2018
Editada: Stephen23 el 5 de Feb. de 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 el 14 de Jun. de 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 !!!

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 5 de Feb. de 2018
Editada: Stephen23 el 5 de Feb. de 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 comentarios
Davidra Fantarina ANDRIAMISAINA
Davidra Fantarina ANDRIAMISAINA el 5 de Feb. de 2018
Thanks, it works but can you explain this idx thing please
Stephen23
Stephen23 el 5 de Feb. de 2018
Editada: Stephen23 el 5 de Feb. de 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),...]

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Workspace Variables and MAT-Files en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by