フィルターのクリア

What do these lines of code mean

1 回表示 (過去 30 日間)
Camden Nelson
Camden Nelson 2023 年 2 月 11 日
コメント済み: Steven Lord 2023 年 2 月 11 日
I am working on a homework assignment where I have to code a linear search algorithm, and looked up a video to see other solutions. I am confused what the code on lines 2 and 6 mean practically. Is it first initializing an empty array than storing the found user value into that array?
See code below:
1) x = input('Enter the array:');
2) Y = [];
3) y = input('Enter the number you want to seach:');
4) for i=1:length(x)
5) if (x(i)==y)
6) Y = [Y i];
7) end
8) end

回答 (2 件)

Walter Roberson
Walter Roberson 2023 年 2 月 11 日
Yes. That code starts with an empty output, and then each time it finds a match, it appends the index of the match at the end of the list.
  1 件のコメント
Camden Nelson
Camden Nelson 2023 年 2 月 11 日
Ah I see. Thank you!

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


Voss
Voss 2023 年 2 月 11 日
"Is it first initializing an empty array"
Yes.
"[then] storing the found user value into that array?"
Storing the index (i) at which the user's value was found. Specifically, line 6 is storing all the indices at which the user's value was found, and doing so by concatenating them one-by-one with the array Y, and storing the result as the new Y each time.
Consider the following code. Each time, Y = [Y i]; appends a new value to the end of Y by concatenating the existing Y with the new value i.
Y = [];
i = 2;
Y = [Y i]
Y = 2
i = 5;
Y = [Y i]
Y = 1×2
2 5
i = 10;
Y = [Y i]
Y = 1×3
2 5 10
  2 件のコメント
Camden Nelson
Camden Nelson 2023 年 2 月 11 日
Okay gotcha. That makes a lot more sense seeing it step by step. Thanks!
Steven Lord
Steven Lord 2023 年 2 月 11 日
FYI for future reference, you can step through code line by line using the debugging tools if that helps you more easily understand what the code is doing.

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

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by