For loop indexing issue
조회 수: 43 (최근 30일)
이전 댓글 표시
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
Lucas Carvalho
2015년 6월 1일
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
2015년 6월 1일
편집: Lucas Carvalho
2015년 6월 1일
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
답변 (1개)
Star Strider
2015년 6월 1일
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
Star Strider
2015년 6월 1일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!