how can I store this data in an array using loop?

Hello. I am trying to run the below code. but its not working. I want to run the loop 5 times and calculate the value of x for 5 temperatures and store in a matrix.
please help. thanks
a=1;
v=2;
p=1e-5;
vac=zeros(1,5);
T=[77,295,600,750,1234];
for i=1:length(T)
x=exp(a)*exp(-v/(p*T));
vac(i)=x;
end

 採用された回答

Birdman
Birdman 2018 年 1 月 18 日

1 投票

You don't need a loop. Try the following:
vac=exp(a).*exp(-v./(p.*T))

4 件のコメント

Farhan Ashraf
Farhan Ashraf 2018 年 1 月 18 日
Hello, thank you for your time It's giving the following error. "Matrix dimensions must agree"
Birdman
Birdman 2018 年 1 月 18 日
編集済み: Birdman 2018 年 1 月 18 日
It should not. Clear your workspace area and rerun the code.
a=1;
v=2;
p=1e-5;
T=[77,295,600,750,1234];
vac=exp(a).*exp(-v./(p.*T))
Guillaume
Guillaume 2018 年 1 月 18 日
編集済み: Guillaume 2018 年 1 月 18 日
Note that the only operator that should absolutely be dotted is the ./. The others are multiplications with scalar so either .* or * work.
Farhan Ashraf
Farhan Ashraf 2018 年 1 月 18 日
Thank you very much

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

その他の回答 (1 件)

Guillaume
Guillaume 2018 年 1 月 18 日

1 投票

You forgot to mention what it is not working mean: You get error using / Matrix dimensions must agree. That's because you forgot to index T so you're dividing a scalar by a vector which is not a valid matrix operation, so one way to fix your problem:
x = exp(a)* exp(-v/(p*T(i)));
However, you don't need a loop at all, you could use vectorised operations. For that you need to use ./ instead of /:
a = 1; v = 2; p = 1e-5; %constants
T = [77, 295, 600, 750, 1234];
vac = exp(a)*exp(-v./(p*T)) %no loop needed

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by