Nesting loops, inserting numbers into arrays.

1 次查看(过去 30 天)
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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by