For loop indexing issue
43 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
The relevant code is:
for ii = 1:v
if v(ii) ~= a
y = [v(ii)]
elseif v(ii) == a
y = [y b c]
end
w = y
end
v being a vector of unknown length, w being the output of the function. Anyway, the problem is it's only checking for ii = 1; all other values of ii are being ignored. The code runs without errors- it's just running incorrectly. (If you can't tell I'm new to matlab, probably very obvious answer...)
2 comentarios
Lucas Carvalho
el 1 de Jun. de 2015
Hello Heather!
Since you are writing just one number for indexing (ii = 1), it will only evaluate the code for this situation. Try writing this:
for ii = 1:length(v)
Lucas Carvalho
el 1 de Jun. de 2015
Editada: Lucas Carvalho
el 1 de Jun. de 2015
By the way, you can see the definition of length() function and any other function on Matlab using the command help. For example:
help length
Respuestas (1)
Star Strider
el 1 de Jun. de 2015
You probably want to do:
for ii = 1:length(v)
however that’s not the only problem, since ‘w’ will return only the result of the last iteration of the loop. I don’t know what you’re doing, but since in each iteration ‘w’ can be either one or three elements long, you probably want to use a cell array to store the output:
w{ii} = y;
3 comentarios
Star Strider
el 1 de Jun. de 2015
My pleasure!
I thought you were saving everything in ‘w’, and ‘y’ was just a temporary variable in the loop.
The way I read your code (likely the way MATLAB reads it as well), your loop iterates through the elements of ‘v’, and if that element is not equal to ‘a’, it stores the current value of ‘v’ in ‘y’. If that element is equal to ‘a’, it stores the triplet [y b c] in ‘y’ (I assume ‘b’ and ‘c’ are defined elsewhere, and you also initialised ‘y’ before the first iteration). At the end of that iteration, it stores ‘y’ for that iteration as the ii-th element of ‘w’.
You didn’t describe what you want to do, so I have no idea if your code does it.
I created ‘w’ as a cell array, so it contains one assignment of ‘y’ for each iteration of the loop. You would access the fifth element of ‘w’ as: w{5} for instance (note the curly {} brackets), so all the data are there. Because every element of ‘w’ is potentially a different size, the cell array is necessary.
Ver también
Categorías
Más información sobre Startup and Shutdown 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!