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

查看:66
本文介绍了如何在 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

如果您不需要知道 i,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天全站免登陆