How can I access multiples areas in one array without using a for-loop?
Mostrar comentarios más antiguos
I have a array A with 20 000 000 x 1 elements, and two vectors b & c with 500000x1 elements each. now I want to set the areas form b(1:500000):c(1:500000) to zero. I can write it with a for loop but this takes very long:
if true
for i=1:size(b,1)
A(b(i):c(i))=0;
end
end
Thats why I thought I can use:
if true
A(b:c)=0;
end
but it sets only A(b(1):c(1)) to zero and ignores the other elements of the vector.
do you know a fast fucntion to acess the areas at once? Thanks!
8 comentarios
Could you show with a small example what you have in A, b and c as well as the desired output? From the for loop it seems that you have 500k intervals of data that you want to target, where interval i is from a(i) to b(i)
Is that correct?
Walter Roberson
el 24 de Jul. de 2018
Do we need to be concerned with overlap? For example b(5) = 11, c(5) = 15, b(19) = 14, c(19) = 16 would have the same effect as b(5) = 11, c(5) = 16
Katharina Loy
el 24 de Jul. de 2018
Guillaume
el 24 de Jul. de 2018
How are b and c created? As I answered, I don't think that there is a way to make your code faster once you have b and c but it may be possible to improve the code before that to create something easier to work with (e.g. a logical array)
Katharina Loy
el 24 de Jul. de 2018
So if I understand correctly, you want to set to 0 all the positive values when A changes from negative to positive without passing through 0 and all the negative values when A changes from positive to negative without passing through 0?
Also, A(:, 3) is the sign of A(:, 1) except you're using 2 instead of 1 for positive values. Any reason for that 2?
Also, note that your last DiffTime, if not 0, is calculated incorrectly. You should always add 1, so your
if DiffTime(end) ==0 % if Duration is 0
DiffTime(end)= 1;
end
should be replaced by
DiffTime(end) = DiffTime(end) + 1;
or even better, get it right in the first place with:
DiffTime = [diff(Diffrows); size(A, 1)-Diffrows(end,1)+1]; %no need for further adjustment.
Note that size(A(:, 3), 1) is simply size(A, 1)
Katharina Loy
el 24 de Jul. de 2018
Respuesta aceptada
Más respuestas (1)
Guillaume
el 24 de Jul. de 2018
With arrays that size, the fastest is probably the loop you have written.
With smaller arrays, you could do:
indices = 1:numel(A);
tozero = any(indices > a(:) & indices < b(:)); %assuming R2016b or later for implicit expansion
A(tozero) = 0;
However, that requires a temporary 20000000 x 500000 array which would take over 745 GB of memory.
1 comentario
Katharina Loy
el 24 de Jul. de 2018
Categorías
Más información sobre Resizing and Reshaping Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!