Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
786 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use linear indexing to access each element.

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

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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...