How could this code be vectorized? (2025)

1 view (last 30 days)

Show older comments

Fredrik P on 18 Jan 2024

  • Link

    Direct link to this question

    https://matlabcentral.mathworks.com/matlabcentral/answers/2071696-how-could-this-code-be-vectorized

  • Link

    Direct link to this question

    https://matlabcentral.mathworks.com/matlabcentral/answers/2071696-how-could-this-code-be-vectorized

Answered: Voss on 18 Jan 2024

Accepted Answer: Cris LaPierre

Open in MATLAB Online

How can I vectorize this code? I suspect that it can be solve using ndgrid and sub2ind as my last question was. But I just don't get how it should be done. (I'm aware that the vectorized code might very well be slower than the loop-based code. RIght now, I'm just hoping to learn how it should be done.)

close; clear; clc;

n1 = 400;

n2 = 9;

n3 = 2;

A1 = rand(n1, n2, n3);

A2 = rand(n1, n2, n3);

A3 = rand(n1, n2, n3);

[~, B] = max(A3, [], 3);

[C11, C21, C31] = version1(A1, A2, A3, B, n1, n2, n3);

% [C12, C22, C32] = version2(A1, A2, A3, B, n1, n2, n3);

% disp([isequal(C11, C12), isequal(C21, C22), isequal(C31, C32)]);

disp(timeit(@() version1(A1, A2, A3, B, n1, n2, n3)));

4.4875e-04

% disp(timeit(@() version2(A1, A2, A3, B, n1, n2, n3)));

function [C1, C2, C3] = version1(A1, A2, A3, B, n1, n2, n3)

C1 = nan(n1, n2);

C2 = C1;

C3 = C1;

for j2 = 1:n2

for j1 = 1:n1

C1(j1, j2) = A1(j1, j2, B(j1, j2));

C2(j1, j2) = A2(j1, j2, B(j1, j2));

end

end

end

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

Sign in to answer this question.

Accepted Answer

Cris LaPierre on 18 Jan 2024

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2071696-how-could-this-code-be-vectorized#answer_1392616

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2071696-how-could-this-code-be-vectorized#answer_1392616

Edited: Cris LaPierre on 18 Jan 2024

Open in MATLAB Online

I'd just have your max function return the linear index instead of the index. Then use that to index A1, A2, and A3

% your current solution

n1 = 400;

n2 = 9;

n3 = 2;

A1 = rand(n1, n2, n3);

A2 = rand(n1, n2, n3);

A3 = rand(n1, n2, n3);

[~, B] = max(A3, [], 3);

[C11, C21, C31] = version1(A1, A2, A3, B, n1, n2, n3);

% Function definition move to the bottom of script

Here is how you would do it using linear indexing

[~, B1] = max(A3, [], 3,'linear');

C111 = A1(B1);

C211 = A2(B1);

C311 = A3(B1);

Now compare the results to see if they are the same.

isequal(C11, C111)

ans = logical

1

isequal(C21, C211)

isequal(C31, C311)

ans = logical

1

As you can see, the results are equal.

% function moved to bottom of script

function [C1, C2, C3] = version1(A1, A2, A3, B, n1, n2, n3)

C1 = nan(n1, n2);

C2 = C1;

C3 = C1;

for j2 = 1:n2

for j1 = 1:n1

C1(j1, j2) = A1(j1, j2, B(j1, j2));

C2(j1, j2) = A2(j1, j2, B(j1, j2));

C3(j1, j2) = A3(j1, j2, B(j1, j2));

end

end

end

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

More Answers (1)

Voss on 18 Jan 2024

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2071696-how-could-this-code-be-vectorized#answer_1392631

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2071696-how-could-this-code-be-vectorized#answer_1392631

Open in MATLAB Online

n1 = 400;

n2 = 9;

n3 = 2;

A1 = rand(n1, n2, n3);

A2 = rand(n1, n2, n3);

A3 = rand(n1, n2, n3);

[~, B] = max(A3, [], 3);

[C11_v1, C21_v1, C31_v1] = version1(A1, A2, A3, B, n1, n2, n3);

[C11_v2, C21_v2, C31_v2] = version2(A1, A2, A3, B, n1, n2, n3);

% compare the results

isequal(C11_v1,C11_v2)

ans = logical

1

isequal(C21_v1,C21_v2)

ans = logical

1

isequal(C31_v1,C31_v2)

ans = logical

1

function [C1, C2, C3] = version2(A1, A2, A3, B, n1, n2, n3)

[RR,CC] = ndgrid(1:n1,1:n2);

idx = sub2ind([n1,n2,n3],RR,CC,B);

C1 = A1(idx);

C2 = A2(idx);

C3 = A3(idx);

end

function [C1, C2, C3] = version1(A1, A2, A3, B, n1, n2, n3)

C1 = nan(n1, n2);

C2 = C1;

C3 = C1;

for j2 = 1:n2

for j1 = 1:n1

C1(j1, j2) = A1(j1, j2, B(j1, j2));

C2(j1, j2) = A2(j1, j2, B(j1, j2));

C3(j1, j2) = A3(j1, j2, B(j1, j2));

end

end

end

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

Sign in to answer this question.

See Also

Categories

Code GenerationEmbedded CoderDeployment, Integration, and Supported HardwareEmbedded Coder Supported HardwareTexas Instruments C2000 Processors

Find more on Texas Instruments C2000 Processors in Help Center and File Exchange

Tags

  • vectorization

Products

  • MATLAB

Release

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


How could this code be vectorized? (4)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contact your local office

How could this code be vectorized? (2025)

FAQs

How to vectorize a code? ›

Vectorizing code is a technique that will typically enable you to create faster and more readable code. Vectorization is the process of performing computation on a set of values at once instead of explicitly looping through individual elements one at a time. The difference can be readily seen in a simple example.

What does it mean when a code is vectorized? ›

Vectorized code refers to operations that are performed on multiple components of a vector at the. same time (in one statement).

What do you mean by vectorization? ›

Vectorization in computer science refers to the strategy of utilizing pre-existing compiled kernels to perform operations all at once, instead of using loops for repeated operations. It helps in improving runtime performance significantly by executing operations more efficiently.

What does it mean to vectorize in Python? ›

Vectorization is the process of converting an algorithm from operating on a single value at a time to operating on a set of values (vector) at one time. Hence, we can use these techniques to perform operations on Numpy arrays without using loops.

How do you vectorize? ›

Pick an image and give it a try with these steps:
  1. Open your image. ...
  2. Select the part of the image you want to vectorize. ...
  3. Add a Threshold layer. ...
  4. Select Tonal Areas with the Color Range Command. ...
  5. Convert your selection into a path. ...
  6. Create a solid color layer. ...
  7. Save the Vector Image as an SVG file.

How to vectorize code in C++? ›

There are two ways to vectorize a loop computation in a C/C++ program. Programmers can use intrinsics inside the C/C++ source code to tell compilers to generate specific SIMD instructions so as to vectorize the loop computation. Or, compilers may be setup to vectorize the loop computation automatically.

What are vectorization methods? ›

Vectorization in Natural Language Processing (NLP) is a method used to convert text data into a numerical representation that Machine Learning algorithms can understand and process.

How is data vectorized? ›

Vectorization is the process of converting data into numerical vectors that represent essential features. This transformation is especially useful in fields like natural language processing (NLP) and computer vision, where unstructured data needs to be represented in a form that algorithms can understand.

Does vectorization of code make it faster? ›

Speed: Vectorized operations are significantly faster than traditional loop-based approaches. This is because NumPy is optimized to carry out element-wise operations on arrays efficiently. Readability: Vectorization simplifies your code and enhances its clarity.

What does vector mean in coding? ›

What Does Vector Mean? A vector, in programming, is a type of array that is one dimensional. Vectors are a logical element in programming languages that are used for storing a sequence of data elements of the same basic type. Members of a vector are called components.

What is vectorized code in NumPy? ›

Vectorized operations in NumPy enable the use of efficient, pre-compiled functions and mathematical operations on NumPy arrays and data sequences. Vectorization is a method of performing array operations without the use of for loops.

Why do we vectorize? ›

Why Do We Vectorize Our Text? Vectorizing text is the only way computers understand words. Unlike humans who comprehend language through context and semantics, computers rely on numerical data. By converting text into numerical vectors, we give computers a way to process and analyze language.

How do you turn something into a vector? ›

How to Vectorize an Image in 9 Steps
  1. Step 1: Open Your Image in Adobe Illustrator. ...
  2. Step 2: Open the Image Trace Panel. ...
  3. Step 3: Activate the Preview. ...
  4. Step 4: Explore the Presets (Optional) ...
  5. Step 5: Adjust the Settings. ...
  6. Step 6: Initiate the Trace Process. ...
  7. Step 7: Expand the Image. ...
  8. Step 8: Make Edits (Optional)
Dec 5, 2023

How do I turn text into a vector image? ›

How to use Text to Vector Graphic.
  1. Open Illustrator. If you don't have an Illustrator subscription, sign up for a free trial. ...
  2. Locate the Text to Vector Graphic tools. Create a new project in Illustrator or open a pre-existing one. ...
  3. Generate your graphic. ...
  4. Fine-tune your results. ...
  5. Edit your vector. ...
  6. Go further.

What is a vector file code? ›

Vector files are images that are built by mathematical formulas that establish points on a grid. Raster files are composed of the colored blocks commonly referred to as pixels.

How to create a vector on Python? ›

Creation of a Vector in Python
  1. numpy. array(list)
  2. import numpy as np lst = [10,20,30,40,50] vctr = np. array(lst) vctr = np. ...
  3. Vector created from a list: [10 20 30 40 50]
  4. import numpy as np lst = [[2], [4], [6], [10]] vctr = np. array(lst) vctr = np. ...
  5. Vector created from a list: [[ 2] [ 4] [ 6] [10]]
  6. vector + vector.
Aug 3, 2022

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Laurine Ryan

Last Updated:

Views: 5419

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.