필터 지우기
필터 지우기

Size of a matrix after conditions is incorrect.

조회 수: 2 (최근 30일)
Isai Fernandez
Isai Fernandez 2018년 9월 22일
댓글: Isai Fernandez 2018년 9월 22일
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
Isai Fernandez
Isai Fernandez 2018년 9월 22일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Steven Lord
Steven Lord 2018년 9월 22일
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
Isai Fernandez
Isai Fernandez 2018년 9월 22일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by