for loop with vectors of different dimensions help

1 visualización (últimos 30 días)
soloby
soloby el 23 de Jun. de 2015
Comentada: Walter Roberson el 23 de Jun. de 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??

Respuesta aceptada

Walter Roberson
Walter Roberson el 23 de Jun. de 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 comentarios
soloby
soloby el 23 de Jun. de 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 el 23 de Jun. de 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.

Iniciar sesión para comentar.

Más respuestas (1)

Geoff Hayes
Geoff Hayes el 23 de Jun. de 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 comentarios
soloby
soloby el 23 de Jun. de 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 el 23 de Jun. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Debugging and Analysis en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by