MATLAB中For循环中数组的索引子集

时间:2017-05-17 14:53:05

标签: arrays matlab loops

我对MATLAB中的索引和循环有疑问。我有一个长度 n 的向量(在下面的代码中命名为 data )。我想在for循环内一次检查这个向量4个元素。我怎样才能做到这一点?我在下面的尝试不起作用,因为它将超过循环结束时的数组维度。

for k = 1:length(data)

    index = k:k+3;

    cur_data = data(index);

    pre_q_data1 = cur_data(1);
    pre_q_data2 = cur_data(2);
    % Interweaving the data
    q = [pre_q_data1; pre_q_data2];
    qdata = q(:)';


    pre_i_data1 = cur_data(3);
    pre_i_data2 = cur_data(4);

    i = [pre_i_data1; pre_i_data2];
    idata = i(:)';

end    

1 个答案:

答案 0 :(得分:0)

如果您计划索引k,则length(data)不应该k+3一直到for k = 1:length(data)-3 % maximum k = length(data)-3, so maximum index = length(data)-3+3=length(data) index = k:k+3; cur_data = data(k:k+3); % Interweaving the data q = cur_data(1:2); % transpose at end of line here if need be i = cur_data(3:4); % could just use data(k+2:k+3) and not use cur_data end

我也冒昧地大大简化了你的代码,但可以随意忽略它!

    public static KeyPair generateKeyPairRSA()  {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (Exception e) {
        Log.d(TAG,e.getLocalizedMessage());
    }
    return null;
}


public byte[] RSAEncrypt(final String plain, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGO_RSA);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedBytes = cipher.doFinal(plain.getBytes());
    return encryptedBytes;
}

public static PublicKey loadPublicKey1(String stored) throws Exception{
    byte[] data = Base64.decode(stored.getBytes());
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    KeyFactory fact = KeyFactory.getInstance(ALGO_RSA);
    return fact.generatePublic(spec);
}