Size of a matrix after conditions is incorrect.

2 views (last 30 days)
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.
  1 Comment
Isai Fernandez
Isai Fernandez on 22 Sep 2018
For my purposes, I finally solve it:
Mt = (yel < d/2).*(2+yel) + (yel > d/2).*(3-yel);
Instead of conditionals if and loop for.

Sign in to comment.

Answers (1)

Steven Lord
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.
  1 Comment
Isai Fernandez
Isai Fernandez on 22 Sep 2018
I don't get it, I operate manually, and the logic matrices are ready to be used, with the required lengths and values.
Do I must change the yel matrix?
i = 1:length(yel)
i =
Columns 1 through 13
1 2 3 4 5 6 7 8 9 10 11 12 13
Columns 14 through 25
14 15 16 17 18 19 20 21 22 23 24 25
>> yel(i) < d/2
ans =
1×25 logical array
Columns 1 through 19
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0
Columns 20 through 25
0 0 0 0 0 0
>> yel(i) > d/2
ans =
1×25 logical array
Columns 1 through 19
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
Columns 20 through 25
1 1 1 1 1 1

Sign in to comment.

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!