如何在MATLAB中迭代n维矩阵中的每个元素? [英] How do I iterate through each element in an n-dimensional matrix in MATLAB?

查看:498
本文介绍了如何在MATLAB中迭代n维矩阵中的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。我需要在MATLAB中迭代n维矩阵中的每个元素。问题是,我不知道如何为任意数量的维度做这件事。我知道我可以说

I have a problem. I need to iterate through every element in an n-dimensional matrix in MATLAB. The problem is, I don't know how to do this for an arbitrary number of dimensions. I know I can say

for i = 1:size(m,1)
    for j = 1:size(m,2)
        for k = 1:size(m,3)

和等等,但有没有办法做到这一点的尺寸的任意号码?

and so on, but is there a way to do it for an arbitrary number of dimensions?

推荐答案

您可以使用线性索引来访问每个元素。

You can use linear indexing to access each element.

for idx = 1:numel(array)
    element = array(idx)
    ....
end

如果您不需要知道什么,这很有用我,j,k,你在。但是,如果您不需要知道自己的索引,那么最好使用arrayfun()

This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()

这篇关于如何在MATLAB中迭代n维矩阵中的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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