How can I access multiples areas in one array without using a for-loop?
显示 更早的评论
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 个评论
Walter Roberson
2018-7-24
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
2018-7-24
Guillaume
2018-7-24
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
2018-7-24
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
2018-7-24
采纳的回答
更多回答(1 个)
Guillaume
2018-7-24
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!