簡體   English   中英

索引多個數組/矩陣元素,類似於C中的matlab“var [1:10]”

[英]Indexing multiple array/ matrix elements similar to matlab “var[1:10]” in C

對於我的計算,我需要索引到一個數組。 我習慣於MATLAB,你可以用這樣的方式索引

var[1:10]  // extracts the first through to the 10th element of "var"

我試圖在C中找到一個類似的原則,如果可能的話不使用循環。 從研究中我只能看到使用的循環。

如果這是唯一的方法,則可以使用#define或類似的方法來創建一個宏,當你編寫[start:end]它會實現一個循環,但在main代碼中看不到?

我已經編寫了一個可以在幕后實現的基本循環,因為如果有一種方法可以指定這是你想要在[start:end]場景中使用的。

#include <stdio.h>

int main() {
    int array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int start = 3;
    int end = 8;
    int var[5];
    int j = 0;

    for (int i = start; i <= end; i++) {
        var[j] = array[i];
        j++;
    }

    printf("%d", var[5]);
}

我想做一些不可能或不切實際的事情嗎? 對於我想要做的事情,編寫循環或調用函數會使代碼比我想要的更混亂。

for(int i = start; i <= end; i++){

    var[j] = array[i];

    j++;

}

在你的代碼中你的索引我從3到8包括8(因為<=符號而不是<符號)導致6次迭代,其中你的j數組只有5個元素。 你的出境了。

無法在C中更改語法,但如果您只想將數組傳遞到其他位置,則可以將指針傳遞給它。 只是一定不要在函數內部聲明數組,而是在全局空間中。

如果你想對數組做一些操作,你必須在循環中逐個元素地執行它,並且最好為此而不是宏編寫函數。

你可以使用在string.h中聲明的庫函數memcpy,就像這樣。 請注意,您有責任確保目的地有足夠的空間。

#include    <stdlib.h> // for EXIT_SUCCESS
#include    <stdio.h>  // for printf
#include    <string.h> // for memcpy
int main( void)
{
int array[10] = {0,1,2,3,4,5,6,7,8,9};
int start = 3;
int end = 8;
int var[6]; 
    memcpy( var, array+start, (end+1-start)*sizeof array[0]);
    printf("%d\n", var[5]);
    return EXIT_SUCCESS;
}

如果你想要將一個序列從數組復制到數組的另一部分(即如果源和desinations重疊),你應該使用memmove。 它有相同的調用約定。

與python相比,C是低級別的。 編寫C語言意味着要了解其標准庫。

從數組中提取子數組可能有兩個非常不同的含義:

  • 您可以通過將指針傳遞給start元素和end - start的長度來操作子數組end - start一個函數end - start ,該函數需要一個int數組和一個長度的ponter。

  • 但請注意,如果函數修改此子數組,則更改也將在原始數組中進行,因為您正在對此數組的一部分進行操作。

  • 還要注意,數組索引值在開始0在C,不像MATLAB,所以在開始10種元素的切片a具有索引值09

  • 如果您希望提取的子數組不干擾原始數組,則需要一個單獨的數組,可以在示例中定義,也可以使用malloccalloc從堆中分配。

以下是您的代碼的修改版本:

#include <stdio.h>

void print_array(const char *msg, const int *a, int count) {
    printf("%s", msg);
    for (int i = 0; i < count; i++) {
        printf(" %d", a[i]);
    }
    printf("\n");
}

int main() {
    int array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int start = 3;  // start from the third element
    int end = 8;    // stop before the 8th element
    int var[5];     // the extracted slice has 8-3=5 elements indeed

    // print the original array
    print_array("original array:", array, 10);

    // print the slice of the original array from 3 to 8
    print_array("subarray array[3:8]:", array + 3, 8 - 3);

    // extract a copy of the subarray
    for (int i = start; i < end; i++) {
        var[i - start] = array[i];
    }

    // print the extracted array:
    print_array("extracted array:", var, 5);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM