How to obtain vector of specific values in MATLAB
1 次查看(过去 30 天)
显示 更早的评论
Hello all, I want to obtain a 16 vectors each of dimension 96 by 1 such that in 1st vector, the index position 1 to 6 have values 1 and rest of the index position have values zeros.
In 2nd vector the index postion 7 to 12 have value 1 and rest of the index position have values zeros.
In 3rd vector index position 13 to 18 have value 1 rest of the index position have values zeros.
Continuing in this manner, in 16th vector the index position 91 to 96 have value 1 and at all other index positions the value is zero.
Any help in this regard will be highly appreciated.
0 个评论
采纳的回答
Vilém Frynta
2023-3-17
编辑:Vilém Frynta
2023-3-17
Hello,
this looks like homework. I'd like to give you a little bit of a direction, but then you need to try by yourselves.
Because your vector mostly consists of zeros, I would begin by creating vector with zeros:
v1 = zeros([1 96]) % create vector of zeros with 96 columns
Now, use indexing to assign values to your position of choice. For your example, you want to assign number 1 to position from 1 to 6.
v1(1,1:6) = 1 % assign 1 to row 1 and columns 1–6
Now, you can do the rest of the vectors in the similar manner. There is definitely an option to do this with for loop, but I will leave that up to you.
Hope I helped.
更多回答(2 个)
Dyuman Joshi
2023-3-17
It's not a good idea to dynamically define variables. Read - Why Variables Should Not Be Named Dynamically
You can make a 96x16 matrix, in which nth column corresponds to nth vector as required. In this way, your data is easy to access via indexing.
temp=ones(6,1);
out=temp;
for k=1:15
out=blkdiag(out,temp);
end
disp(out)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!