如何在Matlab中分配一组坐标? [英] how to assign a set of coordinates in Matlab?

查看:271
本文介绍了如何在Matlab中分配一组坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab中有三个向量,I(整数),J(整数)和V(双精度). 我想在位置I_i,J_i上分配一个矩阵,范围为i,值V_i.

I have three vectors in Matlab, I (of integers), J (of integers) and V (of doubles). I want to assign to a matrix, in positions I_i,J_i, ranging over i, value V_i.

有可能吗? 问题在于A(I,J)引用了所有可能的组合(I_i,J_j),而不是匹配向量中的元素.

Is that possible? The problem is that A(I,J) refers to all possible combinations (I_i,J_j) instead of matching the elements in the vector.

推荐答案

简短的答案是这样的:

 A(sub2ind(size(A),X,Y)) = V

尝试一下,它就像一种魅力.

Try it out, it works like a charm.

如果您有好奇心并且想要它,可以很容易地按照以下说明进行操作:

The explanation, if you're curious and want it, is simple to follow:

Matlab中的每个矩阵都存储为1d数组,即法线向量.

Every matrix in Matlab is stored as a 1d array, a normal vector.

一个2d数组实际上以第一列的顺序存储在内存中,然后是第二列,依此类推.因此,您可以通过线性下标来索引任何Matlab数组,而不必考虑其维度.

A 2d array is actually stored in memory as a sequence of the first column, followed by the second column, and so on. Because of that, you can index any Matlab array, independent of its dimension, by a linear subscript.

例如:

  A =  [1  4  7;
        2  4  8;
        3  6  9 ];

实际存储为:

[1 2 3 4 5 6 7 8 9]

要访问该项目,您需要做的是:(j-1)* num_of_columns + i

So to access item all you have to do is: (j-1)*num_of_columns + i

因此,A(2,3)返回的结果与A(8)相同,即在这种情况下:8;

Because of that, A(2,3) returns the same as A(8), that is, in this case: 8;

在给定矩阵大小的情况下,sub2ind函数将下标"列表转换为线性索引.正是您想要做的.

The sub2ind function transforms a list of "subscripts" to linear indexes, given the size of the matrix. Exactly what you want to do.

有了索引,很容易进行分配.

And with the indexes at hand, it is easy to make the assignment.

文档: sub2ind

在Matlab中建立索引

希望我能正确理解你.

我花了很长时间回答,因为这是Matlab的非常重要的一部分,并且很多人使用向量运算"功能使代码过于复杂,以致于无法使用普通索引完成操作.

I took the time to answer in a long fashion because this is a very important part of Matlab, and a LOT of people overcomplicate the code using the "vector-operating" functions to do things that could be done with normal indexing.

这篇关于如何在Matlab中分配一组坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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