Fill a zeros matrix with another matrix until it is full
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Sumara
2019-6-14
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 !!!
采纳的回答
Stephen23
2018-2-5
编辑:Stephen23
2018-2-5
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 个评论
Stephen23
2018-2-5
编辑:Stephen23
2018-2-5
"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),...]
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!