logo
down
shadow

How could I vectorize this for loop?


How could I vectorize this for loop?

By : Sam Zimmerman
Date : November 15 2020, 06:54 AM
wish of those help Since multiple entries in data[i] might contain the same value, I don't see how this could be vectorized simply since there can be race conditions. The point of vectorization is that each element is independent of the other elements, and so can be computed in parallel. But your algorithm doesn't allow that. "Vectorize" is not the same thing as "make go faster."
What you seem to be building here is a histogram, and iOS has built-in, optimized support for that. You can create a single-channel, single-row image and use vImageHistogramCalculation_Planar8 like this:
code :
void f1(unsigned char *data, unsigned int size) {
    unsigned long A[256] = {0u};

    vImage_Buffer src = { data, 1, size, size };
    vImage_Error err = vImageHistogramCalculation_Planar8(&src, A, kvImageDoNotTile);
    if (err != kvImageNoError) {
        // error
    }
    ...
}


Share : facebook icon twitter icon
Refactoring/Vectorize a simple for loop (example data and loop included)

Refactoring/Vectorize a simple for loop (example data and loop included)


By : developer
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Here is the sample code , Aren't you just doing
code :
sif <- matrix(s, ncol=N, byrow=T)
sif <- matrix(s[1:(round(length(s)/N)*N)], ncol=N, byrow=T)
> max(abs(sif[1:9999,1:100]-sif2[1:9999,1:100]))
[1] 0
> sif[10000,]
[1] 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 ...
sif2[nrow(sif2), ] <- nrow(sif2)
               User      System     elapsed 
Your way     57.831      14.056      71.525 
R's way       0.004       0.002       0.006  
Trying to vectorize a for loop in R

Trying to vectorize a for loop in R


By : Rajesh
Date : March 29 2020, 07:55 AM
may help you . In general, try to avoid if when not needed. I think your desired output can be built as follows.
code :
model <- unlist(sapply(1:length(model.list), function(i) model.list[[i]][model.lookup[[i]]]))
model[model=='']<-NA
Vectorize the following for loop

Vectorize the following for loop


By : khodaei-m
Date : March 29 2020, 07:55 AM
With these it helps Approach #1
The way I see it as, you would have a bottleneck with the cell2mat inside the loop. If you are running it for considerable number of loop iterations, this bottleneck would be felt. So, with this post I would try to re-organize the input array a so that the cell2mat would be used on it once outside the loop. That would be used to extract all elements and then re-group cell elements into another cell array, whose each cell would hold values corresponding to the cell2mat() extracted values at each iterations with the original code. Thus, each cell of such a re-organized cell array could be fed directly to replace cell2mat(a(a{elem})).
code :
% Re-organize a to create another cell array in which each cell
% would have "cell2mat(a(a{elem}))" for iterator elem
lens = cellfun('length',a)
arr = [a{:}]
cumlens = cumsum(lens(arr))
grouped_cumlens = cumlens(cumsum(lens))
grouped_a = mat2cell(cell2mat(a(arr)),1,diff([0 grouped_cumlens]))

% Use grouped_a to perform the same operations but without cell2mat in loops
outx = 0;
for elem = i
    outx = outx + sum(ismember(grouped_a{elem},b{elem}));
end
% Code un-changed from the previous version
lens = cellfun('length',a)
arr = [a{:}]
cumlens = cumsum(lens(arr))
grouped_cumlens = cumlens(cumsum(lens))

% Extract data into a regular array and decide start and stop indices
data = cell2mat(a(arr))
starts = [1 grouped_cumlens(1:end-1)+1]
stops = grouped_cumlens

% Use extracted data with its start,stop indices for each iteration
outx = 0;
for elem = i
    outx = outx + sum(ismember(data(starts(elem):stops(elem)),b{elem}));
end
How to vectorize this for loop

How to vectorize this for loop


By : MDombrowski
Date : March 29 2020, 07:55 AM
wish helps you In this case you need to transform your subscripted indexes stored in x_cords and y_cords into linear indexes using the sub2ind-function and then you can directly assign the ones like this:
code :
buffImg=zeros(100,100);
x=randperm(100);
y=randperm(100);
buffImg(sub2ind(size(buffImg),x,y))=1;
x=randperm(100);
y=randperm(100);
buffImg=zeros(100,100);
buffImg2=zeros(100,100);
for i = 1:length(x)
   buffImg(x(i),y(i)) = 1;
end
buffImg2(sub2ind(size(buffImg),x,y))=1;
all(all(buffImg==buffImg2))
selective `for` loop for an R function: `for` loop Or `Vectorize`

selective `for` loop for an R function: `for` loop Or `Vectorize`


By : 曹先胜
Date : March 29 2020, 07:55 AM
Does that help I highly appreciate the answer by our colleague @r2evans, but I think this problem might have a bit simpler solution (i.e., one line of if syntax):
code :
ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

p = if(length(m) > 1) function(x) dnorm(x, m[i], s) else function(x) dnorm(x, m, s[i])

for(i in 1:loop){
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
 }
}
# Example of use:
ab(m = c(0, 1), 1)
#Example of use:
ab(m = 0, c(1, 2))
Related Posts Related Posts :
  • Update tableView row from AppDelegate Swift 4
  • Assigning return value of a class method to a variable error
  • how to display circular progress in delphi ios apps?
  • I can't figure how to fix this Expected identifier or '('
  • How to Test APIs in Swift 4?
  • Link error /Build/Products/Debug-iphonesimulator file not found
  • working with a very large JSON object in iOS
  • Turn off part of the iPhone Screen
  • Phonegap 3.0 app with facebook login using xCode
  • How to add interstitial admob ads to my ios project
  • adding tapku calendar to ios app
  • Add an alertcontroller in a global swift file?
  • Take square image with Cordova (Phonegap) Camera API?
  • Amazon S3 policy allowing only upload not overwrite
  • How to change the UILabel content by tapping?
  • Adding checkmark to selected table cell also checks another table cell
  • UICollectionView cellForItemAtIndexPath indexPath row is nil
  • Resize and set quality on JPEG image while retaining EXIF in iOS
  • How to push rootviewcontroller in Ios
  • How to add UIBarbuttonItem at centre on UInavigationbar in iOS
  • Would this IOS device test crash be expected
  • PickerView not showing any values
  • How to set root view controller in storyboard animated with navigation controller programmatically
  • Can anyone suggest me the effective way to deal with s3 upload fail because of timezone difference issue?
  • Getting list of files in documents folder
  • Error while using Realm Object as a singleton. Is it a good idea?
  • inserting into SQLite database
  • More nodes than I should
  • Facebook IOS SDK navigate to another controller after login not working
  • Swift Array - use "Contains" of type AnyObject
  • Sidebar menu with indicate navigationbar on iOS
  • Programmatically set size of UIView from Storyboard
  • Navigation bar blink
  • Web services issue on POST method
  • Parse.com error 'Method not allowed when Pinning is enabled.' when I use a PFQueryTableViewController subclass
  • Swift can't send URLRequest at all?
  • No Provisiong profiles with a valid signing identity were found and Failed to locate or generate matching signing assets
  • iOS: how to set httponly flag for NSHTTPCookie
  • How to get the mac address of a beacon in objective-c without knowing its UUID, major and minor values?
  • tableView is not showing data from JSON in swift
  • iTunes reject app for date of birth
  • SWIFT reporting "Extra argument in call" - works in Playground
  • save data depending on passed value in swift
  • webview not showing on full Screen of iphone 6
  • Location Notification's based on Latest iOS Feature
  • Adjusting Height of UITableViewCell
  • How to show five digit unicode in iphone
  • unwind doesn't work
  • Confusion about coordinates, frames & child nodes in SpriteKit on iOS?
  • If Statements not being recognized by Xcode
  • readonly property in RubyMotion
  • 'No available types for source 1' when the app runs on my device(IPhone 6) swift
  • IOS:Remove view when clicked in background
  • Removing "\" from URL in iOS Swift
  • iOS - Send an email automatically (NOT from user's account)
  • The usage of NSNotificationCenter in the relationship of parent and children
  • When do Apple auto-renewable subscriptions renew?
  • Unknown large spacing between x-axis label and base of plot in core-plot
  • How do I change the displayed time format after NSTimer is initiated?
  • Swift JSON breaks when [ ] are used
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org