MATLAB to C++: Converting Array Generation with std::vector
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>: Thestd::vectorcontainer is used to define theY_ImageandX_Imagearrays. It is a dynamic array that can grow as needed.forloop: This loop iterates from -400 to 400 with a step size oftho_R, adding each element to theY_ImageandX_Imagevectors usingpush_back().std::cout: Thestd::coutobject 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.
原文地址: https://www.cveoy.top/t/topic/pgkL 著作权归作者所有。请勿转载和采集!