nested loops for 2 different variables

This is the code I am trying to run, and I am unsure what is wrong with my nested loops.
Context: I am trying to the find the different values of c and l and calculate the associated costs Cc and Cl for both values . Ultimately I'd like to plot both results to see which combinations of c and l are cheapest. Thank you.
clc;clear;
a=0;
c= 200:10:1200;
l= 1:0.5:7;
for i=1:length(c)
for j=1:length(l)
Cc = (10*c)-2000;
Cl = 900+825*l.^2-1725*l;
a=a+c+l;
end
end

1 件のコメント

Michael
Michael 2021 年 1 月 23 日
I actually think vectorizing the code would be much faster? am i right?

サインインしてコメントする。

 採用された回答

VBBV
VBBV 2021 年 1 月 24 日

0 投票

%if true
clc;clear;
a=0;
c= linspace(200,1200,20);
l= linspace(1,7,length(c));
for i=1:length(c)
Cc(i) = (10*c(i))-2000;
Cl(i) = 900+825*l(i)^2-1725*l(i);
end
Vectorizing could be faster but it can also work with loops better.

3 件のコメント

Michael
Michael 2021 年 1 月 24 日
Oh thank you yeah it works. I was struggling to vectorize the codee. I was wondering if it is possible to plot the values, so it is easier to read them?
VBBV
VBBV 2021 年 1 月 24 日
%if true
plot(c,Cc,c,Cl,'-r', 'linewidth',2); grid
You can try other options with plot command as well at
Michael
Michael 2021 年 1 月 24 日
Is it possible to plot these values on a 3D plot?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2021 年 1 月 23 日

コメント済み:

2021 年 1 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by