How do I change all the elements in matrix with an index larger than a certain number to zero?

5 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 27 de Jun. de 2015
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.
  1 comentario
Cyrus Tirband
Cyrus Tirband el 28 de Jun. de 2015
It works perfectly! It just made little sense too me earlier, but upon closer inspection it's pretty logical. I got my own code in the question working a little earlier by adding these in my loop
for i=1:P
B = ones(2,N,K(i));
B(:,:,max(K)) = 0;
A(:,:,:,i) = B;
end
But yours is faster (which was important for my assignment!) and offers more insight. Thanks!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing 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