Size of a matrix after conditions is incorrect.
2 views (last 30 days)
Show older comments
I am writing a loop with conditionals. But, I have an error in the calculation, about the size of a matrix.
This is my minimal code:
clc; clear all; close all;
t = 7.71; % mm
h = 50;
d = h - 2*t;
yel = .01*d:1:h/2;
for i = 1:length(yel)
if yel(i) < d/2
Mt1(1:i) = 2+yel(i);
end
end
for i = 1:length(yel)
if yel(i) > d/2
Mt2(i) = 3-yel(i);
end
end
Mt1
Mt2
The Mt1 and Mt2 matrices should have the same length. I have operate step by step in the Command Window, and it is all right.
Why is the length different if I have the same logic condition when I use if?
I tried to fix it but I couldn't. I hope you help me.
PD. I don't have much experience in Matlab.
Answers (1)
Steven Lord
on 22 Sep 2018
The last element of yel may be greater than d/2, may be less than d/2, or may be neither greater than nor less than d/2. It can't be both greater than d/2 AND less than d/2 simultaneously. So you can't assign to both element length(yel) of Mt1 and element length(yel) of Mt2. They may be the same length if you assign to element length(yel) of neither Mt1 nor Mt2 (if yel(end) is exactly equal to d/2 or is NaN) but usually one will end up at least one element longer than the other.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!