Vectors must be the same length

조회 수: 1 (최근 30일)
nancy robles
nancy robles 2020년 10월 4일
댓글: Image Analyst 2020년 10월 5일
I'm not sure what it means by "vectors must be the same length".
This is my code
i=1;
ct= 0;
Cmftct=0;
Coldct = 0;
Hotct= 0;
while (i <= n)
if (temps(i) <= 32)
Coldct = Coldct + 1;
elseif (temps(i) <=70)
Cmftct = Cmftct +1;
elseif (temps(i) <=99);
Hotct = Hotct +1;
else
Hotct = Hotct +1;
end
i = i +1;
end
figure(1)
x=[i : length(temps)];
y = temps;
plot(x, y, 'Marker', '^', 'Color', 'r', 'LineStyle', ':' ,'LineWidth', 2);
figure(2)
c = categorical(["# of cold Days", "# of Cold Days","# of Comfortable Days", "# of Hot Days"]);
b = [Coldct, Cmftct, Hotct];
bar(c, b);
end

채택된 답변

Image Analyst
Image Analyst 2020년 10월 4일
Lots of problems with that:
  1. Computing x before y so x and y have different lengths
  2. Using while loop instead of vectorized.
  3. c having 4 categories - cold is repeated. Not the same as b which has 3 numbers, not 4.
Here is the fixed code:
temps = 100 * rand(1, 50);
ColdCount = sum(temps <= 32);
CmftCount = sum(temps <= 70);
HotCount = sum(temps > 70);
subplot(2, 1, 1);
y = temps;
x = 1 : length(y);
plot(x, y, 'Marker', '^', 'Color', 'r', 'LineStyle', ':' ,'LineWidth', 2);
yline(32, 'LineWidth', 2, 'Color', 'b');
yline(70, 'LineWidth', 2, 'Color', 'b');
title('Temperature vs. Day', 'FontSize', 18);
xlabel('Day', 'FontSize', 18);
ylabel('Temperature', 'FontSize', 18);
grid on;
subplot(2, 1, 2);
c = categorical(["# of Cold Days","# of Comfortable Days", "# of Hot Days"]);
b = [ColdCount, CmftCount, HotCount];
bar(c, b);
ylabel('Count', 'FontSize', 18);
grid on;
  댓글 수: 2
nancy robles
nancy robles 2020년 10월 4일
How do you get length without using the word length in a array?
Image Analyst
Image Analyst 2020년 10월 5일
When I said:
temps = 100 * rand(1, 50);
I was creating a list of 50 numbers in a row vector. When I say
temps <= 32
that creates a logical vector 50 elements long where each is 0 (false) or 1 (true) as to whether the number in the corresponding temps vector is <= 32 or more than 32. For example [0,0,1,0,1,1,1,0,0,1,1,0,1,......]
Now I don't want the length of any of those vectors - I already know they are 50 elements long, so there is no need to call length(). Plus length() will tell me the length of the entire vector, both 0s and 1s, not just the 1s (or 0s).
When I say
ColdCount = sum(temps <= 32);
that sums up the vector, which sums up the 1's which is the values colder than or equal to 32, which is the count that was wanted. Does that explain it more thoroughly?

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by