For loop only returning first and last iterations correctly
13 views (last 30 days)
Show older comments
variables = [string(mtr1.sti3), string(mtr1.sti3_RESP)];
for i = 1:length(variables);
if variables(i, 1) == string('G1.bmp') & variables(i, 2) == string('1');
corr_RESP = 1;
elseif variables(i, 1) == string('G3.bmp') & variables(i, 2) == string('2');
is_corr = 1;
else
is_corr = 0;
end
corr_RESP(i,:) = [is_corr];
end
The result is a vector of the correct length, with correct output for the first and last iteration but 0s for all other iterations. I can't figure out why. Any suggestions?
PS - I know there is likely a cleaner way to get the result I want but I'm new to matlab and I really only care that my code works.
0 Comments
Accepted Answer
KL
on 5 Oct 2017
Why do you create is_corr. You could directly assign values in corr_RESP.
corr_RESP = zeros(size(variables,1),1); %preallocate corr_RESP with same number of rows as variables
for i = 1:length(variables);
if variables(i, 1) == string('G1.bmp') & variables(i, 2) == string('1');
corr_RESP(i,:) = 1; %assign directly at i-th position
elseif variables(i, 1) == string('G3.bmp') & variables(i, 2) == string('2');
corr_RESP(i,:) = 1;
else
corr_RESP(i,:) = 0;
end
end
Is this what you want?
More Answers (1)
Guillaume
on 5 Oct 2017
Edited: Guillaume
on 5 Oct 2017
Not knowing what the correct length or what the correct output should be. It's difficult to say what is going wrong. So I'll just say what your code is doing and you can see if that's what was intended:
- Whenever the value in the first column of the poorly named variables variable is equal to "G1.bmp" and the 2nd column equal to "1", the content of corr_RESP is deleted, and it is reset to the scalar 1. Possibly, that is why your code is going wrong but that's what you're doing in your if branch.
- If the above is not the case, but happened on the last iteration, then corr_RESP will get expanded to have i rows, the first row being one, from the scalar assignment done by the if branch, rows 0 to i-1 being 0 due to the automatic expansion, and row i being either 0 or 1, depending on the elseif.
*Repeat the above until last row, erasing corr_RESP when the first condition is match and rebuilding it whenever it is not.
As said, we don't know what your intentions where (hint: comments are a must) so it's impossible to say if the above is what you wanted nor how to correct it.
Side note: in recent versions of matlab, string('G1.bmp') can be simplified to "G1.bmp".
Side note 2: Never use length on 2D matrix. In your case, use size(variables, 1). Even on vectors, you're better off using numel.
0 Comments
See Also
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!