在Matlab中将向量作为索引的完整矩阵 [英] Complete matrix with vectors as indices in matlab

查看:801
本文介绍了在Matlab中将向量作为索引的完整矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有一个矩阵A1和两个向量v1和v2,如下所示:

Let us say that we have a matrix A1 and two vectors v1 and v2 as follow:

A1=zeros(5, 5);
v1=[1 2 3];
v2=[5 5 4];

是否有一种方法可以将v1和v2用作索引逐一替换A1的元素?即在A1(1,5),A1(2,5)和A1(3,4)中插入一些元素.

Is there a way to replace the elements of A1 using v1 and v2 as indices one by one? i.e., insert in A1(1, 5), A1(2, 5), and in A1(3, 4) some elements.

以下内容完成v1和v2的所有组合.我只想要一张一张.即v1(1)与v2(1),v1(2)与v2(2),依此类推.

The following do all combinations of v1 and v2. I want only one by one. i.e., v1(1) with v2(1), v1(2) with v2(2), and so on.

A1(v1, v2) 

推荐答案

基本上,您具有行和列信息,需要将它们转换为线性索引,才能索引为A1.为此,请使用 sub2ind -

Basically you have row and column information and need to convert them into a linear index, to index into A1. For this, use sub2ind -

A1(sub2ind(size(A1),v1(1),v2(1))) = 12
A1(sub2ind(size(A1),v1(2),v2(2))) = 10
A1(sub2ind(size(A1),v1(3),v2(3))) = 9

输出-

A1 =

     0     0     0     0    12
     0     0     0     0    10
     0     0     0     9     0
     0     0     0     0     0
     0     0     0     0     0

如果这些值存储在某个数组array1中,请使用与上面相同的结果-

If you have those values stored in some array, array1, use this for the same result as above -

array1 = [12 10 9];
A1(sub2ind(size(A1),v1,v2)) = array1;

这篇关于在Matlab中将向量作为索引的完整矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆