Nesting loops, inserting numbers into arrays.
1 view (last 30 days)
Show older comments
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 Comments
Stephen23
on 2 Jul 2019
David Tejcek's "Answer" moved here:
Sorry I meant, create a new array without the repeated element.
Stephen23
on 2 Jul 2019
"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!
Answers (1)
Vinai Datta Thatiparthi
on 16 Jul 2019
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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!