Creating a series of random numbers, where the next series is changed by a factor with the previous

조회 수: 1 (최근 30일)
For one of my classes, we were assigned a problem where we have to create a series of random numbers that the next series of numbers is the previous multiplied by a factor. We then have to store the numbers in a single matrix.
The code I currently have written keeps appearing with the error code that it is unable to perform the assignment because the left and right sides have a different number of elements. I am looking for advisement on how to change this in order to allow the code to work and fill the matrix.
For this example, I need to create a 5 series, with 25 randon numbers, where the next series is 1/4 of the previous. The numbers produced should be stored in the x single matrix.
The code I started is as follows:
x = zeros(5,25);
count = 1;
for i = 1:5
if i==1
s(count) = randn(1,25);
count = count+1;
elseif i~=1
s(count) = randn(1,25)/4;
count = count +1;
else i == 5
s(count) = count(4,1:25)/4;
end
end

답변 (1개)

Paul
Paul 2022년 9월 24일
Hi Lily,
The code starts by allocating a 5 x 25 matrix, x. That's good. But then x is never used after that. Assuming that x is supposed to contain the final result, you could proceed as follows.
Pre-allocate the result
x = zeros(5,25);
Assign the first row of the result. Note the use of the double indexing of x. Here, x(1,:) means the "row 1, all columns of x"
x(1,:) = randn(1,25);
Note that a variable or an expression can also be used as an index, e.g., if k = 2, x(k,:) is row 2 and x(k-1,:) is row 1.
Now that the first row if x is filled in we only need to fill in rows 2 -5
for i = 2:5
% do something here
end
Maybe these hints will allow you to fill in the code in the loop.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by