# for loop with vectors of different dimensions help

3 views (last 30 days)
soloby on 23 Jun 2015
Commented: Walter Roberson on 23 Jun 2015
x = -10:0.1:10;
y = 0:.005:1;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[3 6 6 9]);
for i = 1:201
y(i) = [x(i),f1(i)]
end
this doesn't seem to work but I dont know why??

Walter Roberson on 23 Jun 2015
x = -10:0.1:10;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[3 6 6 9]);
y = [x(:), f1(:)];
this would produce two columns; you could also use rows like
y = [x; f1];
If you need to use a loop then
x = -10:0.1:10;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[3 6 6 9]);
y = zeros(length(x), 2);
for k = 1 : length(x)
y(k,:) = [x(k), f1(k)];
end
Walter Roberson on 23 Jun 2015
y(k,:) means to take the k'th row (e.g., k=3 would be row #3), and all columns. So all of row #k.

Geoff Hayes on 23 Jun 2015
Soloby - please clarify what you mean by this doesn't seem to work. What is the problem? Are you observing any errors, and if so, what are they? Could it be that the error is In an assignment A(I) = B, the number of elements in B and I must be the same.
Note that you initialize y to be an array of 201 elements and then overwrite each element of y in the for loop. Why? Are you trying to populate y so that it is a 201x1 array. If so, it may be that you want to be doing the following instead
for k = 1:201
y(k,:) = [x(k),f1(k)];
end
Note the use of k as the index variable rather than i since MATLAB uses the latter to represent the imaginary number.
##### 2 CommentsShow 1 older commentHide 1 older comment
Walter Roberson on 23 Jun 2015
It would depend how you initialized y. In your initial code you initialized y as a row vector, so it would be 1 x 201, so when k was 1 you would be trying to assign a two element vector into y(1,:) which is 1 x 141. You need to either not initialize y or initialize y to 141 x 2 like I did in my version.

### 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!