While loop for testing the end of vector (Matlab)

Dear members,
If we have a long vector that we don't know its length, and we want use while loop to repeat the task than stop and exit from the loop when the vector length is at its end.
For example, if the vector length is 10000 bits so we repeat the calculation (of any task) until 10000 than we stop and exit.
But in my case, I don't know the length of my vector. So how can I program this please?
Thank you.

 採用された回答

Rik
Rik 2021 年 2 月 17 日

1 投票

You can use numel to create a loop over a vector of unknown size:
A=rand(1,100);
for n=1:numel(A) % n will go to 100
%your code here
end

5 件のコメント

Afluo Raoual
Afluo Raoual 2021 年 2 月 17 日
But what if I don't know the length of my vector if it is 100 or 100000
Rik
Rik 2021 年 2 月 17 日
numel will deal with that. That first line is just to create some example data. This loop will run 100 times if there are 100 elements in A, and 10k times if there are 10k elements in A.
Afluo Raoual
Afluo Raoual 2021 年 2 月 17 日
Thank you so much
Rik
Rik 2021 年 2 月 17 日
You're welcome. If either answer solved your issue, please consider marking it as accepted answer. If you feel both answers solved your issue, pick the best one and give the other an upvote.
If your issue is not yet resolved, feel free to comment with your remaining issues.
Afluo Raoual
Afluo Raoual 2021 年 2 月 17 日
It's done

サインインしてコメントする。

その他の回答 (1 件)

Daniel Pollard
Daniel Pollard 2021 年 2 月 17 日
編集済み: Daniel Pollard 2021 年 2 月 17 日

1 投票

If you know that it's 1-dimensional, you can use
numel(vector)
which returns the length of your vector. Also useful to know is
size
which returns the size of a matrix (eg, [2 2] for a 2x2 matrix, [10 1] for a 10x1 vector, etc).
Edit I've replaced length with numel - thank you Rik.

3 件のコメント

Rik
Rik 2021 年 2 月 17 日
編集済み: Rik 2021 年 2 月 17 日
I would strongly argue against teaching length. It is either equivalent to numel, or it will introduce a subtle bug that may be hard to catch if the direction of the vector is different from what you expect. I haven't seen a case where it couldn't be replaced by numel or size. Starting in R2020b you can also use the width function, see also this blog (and the comments).
Daniel Pollard
Daniel Pollard 2021 年 2 月 17 日
This is news to me - I've used length multiple times without any issues. What exactly is the bug?
Rik
Rik 2021 年 2 月 17 日
The bug is not with length, the bug is with the use of length. For a vector it is equivalent to numel, and for array inputs it is probably not what you mean. How often did you want to loop over max(size(A)) without knowing which dimension is that maximum?

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

2021 年 2 月 17 日

コメント済み:

2021 年 2 月 17 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by