I get "vectors must be the same length". How come?

13 Ansichten (letzte 30 Tage)
Kevin Solagnier
Kevin Solagnier am 4 Okt. 2022
Beantwortet: Steven Lord am 4 Okt. 2022
syms x
x1 = 0:0.1:5
x2 = 5:0.1:35
x = [x1 x2]
C1 = 15
C2 = 15 - 13/30. * (x2-5)
C = [C1 C2]
plot (x,C)

Antworten (2)

Torsten
Torsten am 4 Okt. 2022
How do you want to plot a vector of length 302 against a vector of length 352 ? It's not possible.
x1 = 0:0.1:5;
x2 = 5:0.1:35;
x = [x1 x2];
C1 = 15;
C2 = 15 - 13/30. * (x2-5);
C = [C1 C2];
numel(x)
ans = 352
numel(C)
ans = 302
plot (x,C)
Error using plot
Vectors must be the same length.

Steven Lord
Steven Lord am 4 Okt. 2022
If you want the value of C1 to be a constant 15 for all the values of x1, you need to explicitly expand C1 to be a vector of that size. MATLAB doesn't "notice that you're going to use x and C in a later call and so automatically expand the size of C1" or anything like that.
x1 = 0:0.1:5;
x2 = 5:0.1:35;
x = [x1 x2];
C1 = repmat(15, size(x1)); % Modified code here
C2 = 15 - 13/30. * (x2-5);
C = [C1 C2];
plot (x,C)
Instead of using repmat you could have multiplied it by an array of ones or added it to an array of zeros of the correct size.
Alternately you could have modified your x1 and your C1 to only include the endpoints.
x3 = [0 5];
C3 = [15 15];
x = [x3, x2];
C = [C3, C2];
figure
plot(x, C)

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by