使用坐标向量访问矩阵值? [英] Access matrix value using a vector of coordinates?

查看:109
本文介绍了使用坐标向量访问矩阵值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个向量:

b = [3, 2, 1];

假设我们也有这样的矩阵:

Let's say we also have matrix like this:

A = ones([10 10 10]);

我想使用向量b作为坐标源来为矩阵A分配值.在此示例中,它等同于:

I want to use vector b as a source of coordinates to assign values to matrix A. In this example it will be equivalent to:

A(3, 2, 1) = 5;

在MALTAB中,是否有一种简单的方法可以将向量用作索引矩阵的坐标源?

Is there an easy way in MALTAB to use a vector as a source of coordinates for indexing a matrix?

推荐答案

您可以通过将向量b转换为单元格数组来实现:

You can do this by converting your vector b into a cell array:

B = num2cell(b);
A(B{:}) = 5;

第二行将B扩展为逗号-分隔的列表,将B的每个元素作为单独的数组索引传递.

The second line will expand B into a comma-separated list, passing each element of B as a separate array index.

如果b包含一个以上点的坐标(每一行代表一个点),则可以将解决方案归纳如下:

If b contains coordinates for more than one point (each row represents one point), you could generalize the solution as follows:

B = mat2cell(b, size(b, 1), ones(1, size(b, 2)));
A(sub2ind(size(a), B{:}))

此处b转换为单元格数组,每个单元格包含同一维的所有坐标.请注意,A(B{:})不会产生我们想要的结果(相反,它将选择左上角和右下角坐标之间的所有元素),因此我们必须执行一个中间步骤,使用<将坐标转换为线性索引a href ="http://www.mathworks.com/help/matlab/ref/sub2ind.html" rel ="nofollow"> sub2ind .

Here b is converted into cell array, each cell containing all the coordinates for the same dimension. Note that A(B{:}) won't produce the result we want (instead, this will select all elements between the top left and bottom right coordinates), so we'll have to do an intermediate step of converting the coordinates to linear indices with sub2ind.

这篇关于使用坐标向量访问矩阵值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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