Reputation: 13
i want to create a single dimensional array in MATLAB inside for loop, please help with below code:
count = 0;
for i=1:10
arr = count;
count = count+1;
end
when i execute this small code i got 9 as result for arr.
Instead of this i want to have an array arr with 10 values of count for each iteration of i, please help.....
Upvotes: 1
Views: 60468
Reputation: 8537
There are several ways to create arrays in Matlab. The ones you will encounter most often are
via a range expression:
a = 1 : 10; % Creates a row vector [1, 2, ... 10]
a = (1 : 10)'; % Creates a column vector [1, 2, ... 10]^T.
via generating functions:
a = zeros(1, 10); % Creates a 1x10 (=row vector) containing 10 zeros.
a = zeros(10, 1); % Creates a 10x1 (=column vector) containing 10 zeros.
Other generating functions are ones
to create vectors/matrices whose elements are
all 1, rand
to generate vectors/matrices with uniformly distributed random numbers,
randn
for random matrices with Gaussian distribution and so on.
via concatenation (this is slow, but easy to implement and sometimes not avoidable):
% Create a vector containing the numbers 1, 4, 9, 16, ... 100.
a = [];
for idx = 1 : 10
a = [a, idx^2]; % Creates a row vector.
% a = [a; idx^2]; % Creates a column vector.
end
via assigning to an array index larger than the current size (again slow if done in a loop):
% Create a vector containing the numbers 1, 4, 9, 16, ... 100.
for idx = 1 : 10
a(idx) = idx^2;
end
Note: I'm not sure if this works in every version of Matlab.
Upvotes: 8
Reputation: 3616
In order to assign a value to an array you need to tell matlab where in the array you want it to go.
First, create an array of zeros the right size with
arr = zeros(1,10);
Then you can assign count
to element i
of arr
with
arr(i) = count;
So the code you provided becomes
count = 0;
arr = zeros(1,10);
for i=1:10
arr(i) = count;
count = count + 1;
end
Of course, as other people have mentioned, there are much easier ways to do this particular task, such as
arr = 0:9;
Where 0:9
is matlab shorthand for 'a row-array containing the integers zero through nine'.
Upvotes: 1
Reputation: 2778
arr = zeros(10,1); % to initialize array
count = 0;
for i=1:10
arr(i) = count;
count = count+1;
end
Upvotes: 4