Saving output of for loop in array

조회 수: 2 (최근 30일)
Raphael Williams
Raphael Williams 2018년 9월 28일
댓글: Aquatris 2018년 9월 28일
Hi, I am trying to save the output of my for loop in an array. Each output will consist of permutations of a previously defined array. I need to save the new array as consisting of my output in a single array.
The code is
Pload = linspace (1,2,4)
For i= eye(10)
P=Pload(randperm(length(Pload)
End
Now I'm trying to save the output in a new matrix.
Trying
Pnew(i,:)=P
Returns an error "index in position I is invalid"
Kindly help

답변 (2개)

Aquatris
Aquatris 2018년 9월 28일
편집: Aquatris 2018년 9월 28일
There are some mistakes and unclear parts in your code. However, using your code, you can save it as;
Pload = linspace (1,2,4)
for i= 1:10
P(i,:)=Pload(randperm(length(Pload)))
end
Unclear part: why are you calling "randperm" function with "length(Pload)" why are you calling "for i = eye(10)"
  댓글 수: 2
Raphael Williams
Raphael Williams 2018년 9월 28일
Thanks for the response. The objective is to vary the values of the variable Pload 10 times while keeping the initial array structure of Pload intact. Hence since Pload is 1×4, and varied 10 times. I intend on storing the output as 1×40. I want to randomly change the position of each element after a loop, but I want the values to remain unchanged. Defining a solution space but rotating the position
Aquatris
Aquatris 2018년 9월 28일
So since you want to convert the 1x4 to 1x40, you should do something like ;
Pload = linspace (1,2,4);
for i= 1:10
index(1+(i-1)*length(Pload):i*length(Pload)) = randperm(length(Pload));
end
Pnew = Pload(index);
Since the Pnew are possible solutions, it might be more convenient to store it as 10x4 matrix instead, in which case you can use below code;
for j =1:10;
Pnew2(j,:) = Pload(index(1+(j-1)*length(Pload):j*length(Pload)));
end

댓글을 달려면 로그인하십시오.


Stephen23
Stephen23 2018년 9월 28일
편집: Stephen23 2018년 9월 28일
Pload = linspace(1,2,4);
N = numel(Pload);
P = repmat(Pload,10,1);
for k = 1:10
P(k,:) = P(k,randperm(N));
end
P = reshape(P.',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