필터 지우기
필터 지우기

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