MATLAB to C++: Converting Array Generation with std::vector

This article demonstrates how to convert MATLAB code that generates arrays using statements like 'Y_Image=(-400:tho_R:400)' and 'X_Image=(-400:tho_R:400)' into equivalent C++ code utilizing std::vector.

MATLAB Code

In MATLAB, these statements generate arrays with elements ranging from -400 to 400, with a step size of tho_R.

C++ Implementation

#include <iostream>
#include <vector>

int main() {
    int tho_R = 10; // Set step size to 10

    std::vector<int> Y_Image;
    std::vector<int> X_Image;

    for (int i = -400; i <= 400; i += tho_R) {
        Y_Image.push_back(i);
        X_Image.push_back(i);
    }

    // Print the arrays
    for (int i = 0; i < Y_Image.size(); i++) {
        std::cout << "Y_Image[" << i << "] = " << Y_Image[i] << std::endl;
    }

    for (int i = 0; i < X_Image.size(); i++) {
        std::cout << "X_Image[" << i << "] = " << X_Image[i] << std::endl;
    }

    return 0;
}

Explanation:

  • std::vector<int>: The std::vector container is used to define the Y_Image and X_Image arrays. It is a dynamic array that can grow as needed.
  • for loop: This loop iterates from -400 to 400 with a step size of tho_R, adding each element to the Y_Image and X_Image vectors using push_back().
  • std::cout: The std::cout object is used to print the array values to the console.

This code demonstrates how to achieve similar functionality in C++ as the MATLAB code using the std::vector container and a for loop for array creation and iteration. You can adapt this code to create and manipulate arrays in various scenarios in your C++ projects.

MATLAB to C++: Converting Array Generation with std::vector

原文地址: https://www.cveoy.top/t/topic/pgkL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录