简体   繁体   English

MATLAB 数组索引和切片

[英]MATLAB array indexing and slicing

Im writing currently rewriting a Matlab script in C.我正在写当前在 C 中重写 Matlab 脚本。 When i get to the last few lines of the Matlab script a for loop is executed and it iterates through an array.当我到达 Matlab 脚本的最后几行时,将执行一个 for 循环并遍历一个数组。 Since i am trying to rewrite the program in C the slicing notation in the Matlab script is confusing me.由于我试图在 C 中重写程序,因此 Matlab 脚本中的切片符号让我感到困惑。 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.我将如何在仅使用 i 和 j 的嵌套 for 循环索引中编写这行代码,因为您显然无法在 c 中切片。 just for reference u = 1, Ubc is 2D array of size (NX+2, NY+2).仅供参考 u = 1,Ubc 是大小为 (NX+2, NY+2) 的二维数组。 Where NX = NY = 40.其中 NX = NY = 40。

Below is the line of code in Matlab i need to translate to for loop indexing.下面是 Matlab 中的代码行,我需要转换为 for 循环索引。

Nx = 40;
Ny = 40;
u = 1;
Ubc = rand(Nx + 2, Ny + 2);
% First the i interfaces
F =   0.5*    u *( Ubc(2:Nx+2,2:Ny+1) + Ubc(1:Nx+1,2:Ny+1)) 
     - 0.5*abs(u)*( Ubc(2:Nx+2,2:Ny+1) - Ubc(1:Nx+1,2:Ny+1));

You can calculate the same in a loop as您可以在循环中计算相同的值

Nx = 40;
Ny = 40;
u = 1;
Ubc = rand(Nx + 2, Ny + 2);
F = zeros(Nx + 1, Ny);
for z1 = 1 : Nx + 1
    for z2 = 1 : Ny
        F(z1, z2) =   0.5*    u *( Ubc(z1 + 1, z2 + 1) + Ubc(z1, z2 + 1)) 
                    - 0.5*abs(u)*( Ubc(z1 + 1, z2 + 1) - Ubc(z1, z2 + 1));
    end
end

You shouldn't use i and j as loop index in Matlab.您不应该在 Matlab 中使用ij作为循环索引。 Both are the imaginary unit.两者都是虚数单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM