Creating a row vector where the index of the vector is not equal to its element value
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Sanwal Yousaf
am 21 Jul. 2015
Bearbeitet: Stephen23
am 21 Jul. 2015
I am working on a problem and i have an idea of how to do most of it but i am not sure how to do its last part. Any help would be appreciated. I am highlighting the part that i am talking about. The statement for the question is as follows:
Write a function called int_col that has one input argument, a positive integer n that is greater than 1, and one output argument v that is a column vector of length n containing all the positive integers smaller than or equal to n, arranged in such a way that no element of the vector equals its own index. In other words, v(k) is not equal to k for any valid index k.*
0 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 21 Jul. 2015
function v = int_col(n)
v = randperm(n)';
t = v == (1:n)';
if any(t)
ii = [find(~t,1,'first');find(t)];
v(circshift(ii,1)) = v(ii);
end
0 Kommentare
Weitere Antworten (1)
Stephen23
am 21 Jul. 2015
Bearbeitet: Stephen23
am 21 Jul. 2015
Because your question does not state anywhere that the output needs to be random, then the answer can be quite simple: just shift all of the values by one place. You can use circshift for this:
>> int_col = @(n) circshift((1:n)',-1);
>> V = int_col(5)
V =
2
3
4
5
1
>> V(1)
ans =
2
>> V(2)
ans =
3
>> V(5)
ans =
1
1 Kommentar
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!