for loop with vectors of different dimensions help

2 views (last 30 days)
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??

Accepted Answer

Walter Roberson
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
  5 Comments
soloby
soloby on 23 Jun 2015
Also, if I were to divide my f1 into 2 pieces, and my first half is all the way up to right before the peak, do you know of a way to make the second half? sorry for bombarding you with a lot of questions, but here's what I mean.
[a,ix]=max(f1);
for k = 1 :ix
lower_1(k,:) = [x(k), f1(k)];
end
would the second half be something like
for k1 = ix:100
upper_1(k,:) = [x(k), f1(k)];
end
again, thank you for your help
Walter Roberson
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.

Sign in to comment.

More Answers (1)

Geoff Hayes
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 Comments
soloby
soloby on 23 Jun 2015
Subscripted assignment dimension mismatch.
Error in practice (line 14) y(k,:) = [x(k),f1(k)];
I don't know why it gives me a dimension error since both x and f1 are 1x201?
Walter Roberson
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.

Sign in to comment.

Categories

Find more on Graphics Performance 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!