Matlab Array indexing and slicing

711 次查看(过去 30 天)
Im writing currently rewriting a Matlab script in C. When i get to the last few lines of the Matlab script a for loop is executed and it iterates through an array. Since i am trying to rewrite the program in C the slicing notation in the Matlab script is confusing me. I have attached the line of code that is troubling me below.
How would i write this line of code in a nested for loop indexing with i and j only, since you cant slice in c obviously. just for reference U and Ubc are 2D arrays of size (NX+2, NY+2). Where NX = NY = 40.
Below is the line of code in Matlab i need to translate to for loop indexing. i want this code translated to matlab for loope style of indexing. I can do the rest in C myself.
% The following implement the bc's by creating a larger array
% for U and putting the appropriate values in the first and last
% columns or rows to set the correct bc's
Ubc(2:Nx+1,2:Ny+1) = U; % Copy U into Ubc
Ubc( 1,2:Ny+1) = U(Nx, :); % Periodic bc
Ubc(Nx+2,2:Ny+1) = U( 1, :); % Periodic bc
Ubc(2:Nx+1, 1) = U( :,Ny); % Periodic bc
Ubc(2:Nx+1,Ny+2) = U( :, 1); % Periodic bc

回答(1 个)

Mario Malic
Mario Malic 2021-2-28
Hi,
The first line replaces a subset of Ubc, with indices being replaced (2:41, 2:41), where matrix U is of the same size. You can make a nested for loop to do this with counters going from 1 to 40 in C because arrays start from 0 in C.
Ubc(2:Nx+1,2:Ny+1) = U; % Copy U into Ubc
These lines are replacing rows or columns in Ubc,
Ubc( 1,2:Ny+1) = U(Nx, :); % Periodic bc
Ubc(Nx+2,2:Ny+1) = U( 1, :); % Periodic bc
Ubc(2:Nx+1, 1) = U( :,Ny); % Periodic bc
Ubc(2:Nx+1,Ny+2) = U( :, 1); % Periodic bc
Indexing in MATLAB is simple, when you have colon it means take all elements in that row or column, depending where the colon is in the code
U(a,b) % a - row, b - column
U(Nx, :) % Take a subset of U(Nxth row, all elements in that row)
MATLAB part for first line, you can do others similarly with only one for loop
for ii = 1 : Nx
for jj = 1 : Ny
Ubc(ii+1, jj+1) = U(ii, jj);
end
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by