Nesting loops, inserting numbers into arrays.

1 回表示 (過去 30 日間)
David Tejcek
David Tejcek 2019 年 7 月 2 日
回答済み: Vinai Datta Thatiparthi 2019 年 7 月 16 日
HI guys,
Could someone explain to me how to answer a question as follows, (may be long):
If I had a amtrix of numbers say 1 2 4 5; 5 6 8 2; 4 10 9 3 , and wanted to write a code so that after each repeated number, the repeated number is then taken out i.e the 5 in the second row would be taken out. How would I do this? Further, if i wanted to print the arrray of numbers in backwards order, how would I make this happen. Thanks and sorry if that is confusing.
  3 件のコメント
Stephen23
Stephen23 2019 年 7 月 2 日
David Tejcek's "Answer" moved here:
Sorry I meant, create a new array without the repeated element.
Stephen23
Stephen23 2019 年 7 月 2 日
"Sorry I meant, create a new array without the repeated element."
Well that is easy, as a few minutes using your favorite internet search engine would have told you. So I presume that you have already made some effort, and just want us to check your attempt. Then please show us what you have tried so far!

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

回答 (1 件)

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi 2019 年 7 月 16 日
Hey David!
From your description, I understand that you want to remove the elements from the given matrix which occur more than once. I’m assuming that after removing these elements, you are replacing them with a 0.
A simple and straight-forward approach to solving the problem could be –
matrix = [1 2 4 5; 5 6 8 2; 4 10 9 3];
matrix = matrix';
for i=1:numel(matrix)
for j=1:i-1
if matrix(i) == matrix(j)
matrix(i) = 0;
end
end
end
matrix = matrix';
The resulting output is –
matrix =
1 2 4 5
0 6 8 0
0 10 9 3
Coming to the second part of your question, I understand that you want to print the elements from the last one to the first.
A simple implementation can be –
matrixReverse = fliplr(flip(matrix));
The output will be –
matrixReverse =
3 9 10 4
2 8 6 5
5 4 2 1

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by