How do I change all the elements in matrix with an index larger than a certain number to zero?
5 次查看(过去 30 天)
显示 更早的评论
I have trouble making a certain matrix even though it seems trivial. For my code I need to make a 4-D matrix A with dimensions 2x100xmax(K)xP where P=8 and K=round(linspace(1000,2000,P)) . The matrix needs to be all ones, except for K indexes larger than the K that corresponds with the P. For example, A(:,:,:,1) should be all ones except for K's larger than 1000 which should be zeros, and A(:,:,:,8) should be solely ones.
I tried code like
P = 8;
K = round(linspace(1000,2000,P));
A = zeros(2,100,max(K),P);
for i=1:P
A(:,:,:,i) = ones(2,N,K(i));
end
But as my command window showed that is clearly not the way to go.
0 个评论
采纳的回答
Geoff Hayes
2015-6-27
Cyrustd - you almost have it, but I think that your code is just missing the range of the third dimension that you wish to be all ones. We know that
K =
1000 1143 1286 1429 1571 1714 1857 2000
so the third (K) indices that are one correspond to 1:1000, 1:1143, 1:1286, ... , and 1:2000. So we need to do something similar in for loop. Try the following
N = 100;
for u=1:P
A(:,:,1:K(u),u) = ones(2,N,K(u));
end
Note how we use 1:K(u) in the third indexing "dimension" of A which will correspond to the size of multidimensional array generated on the right-hand side of the equation.
更多回答(0 个)
另请参阅
类别
在 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!