how to develope loop to save the 'n' elements from the vectors

1 回表示 (過去 30 日間)
gourav pandey
gourav pandey 2021 年 9 月 15 日
コメント済み: Matt J 2021 年 9 月 15 日
clc;
clear;
A= [14,51,2,15,........,7 ] % this is known
p1=A[1]
p2=A[2]
.
.
.
.
.
pn=A[n]
%%% i need to use p1,p2,p3,...pn in another equation. so i dont know to to save this elements from A. how to use loop to that it automatically get saved for n elements

回答 (2 件)

Matt J
Matt J 2021 年 9 月 15 日
It is not a good idea to store A(i) in separate variables. You should probably just write your equation in terms of vector operations on A, which you already have.
  2 件のコメント
gourav pandey
gourav pandey 2021 年 9 月 15 日
Hii Matt, thank you
i fully agree with you. actually, i am a beginner, so no idea how to use.
if my function is in this way
fun= p1*r^2+p2*ln(r)+p3*cos(theta)/r+p4*sin(theta)/r+(pn*r^(-n+2))*cos(n*theta)
then how to do that?
Matt J
Matt J 2021 年 9 月 15 日
A(1)*r^2+A(2)*ln(r)+A(3)*cos(theta)/r+A(4)*sin(theta)/r+(A(n)*r^(-n+2))*cos(n*theta)

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


Awais Saeed
Awais Saeed 2021 年 9 月 15 日
Although it is not prefered to name variables in a loop but if you striclty want to do this in loops than you can use eval(). Note that using this method is NOT RECOMMENDED. It has been said many times in this forum and by MATLAB itself.
clc;
clear;
A= [14,51,2,15,7]
A = 1×5
14 51 2 15 7
for col = 1:1:size(A,2)
eval(['p',num2str(col),'=A(',num2str(col),')'])
end
p1 = 14
p2 = 51
p3 = 2
p4 = 15
p5 = 7
  1 件のコメント
Stephen23
Stephen23 2021 年 9 月 15 日
編集済み: Stephen23 2021 年 9 月 15 日
Note that this is slower and more complex than simply using the vector directly.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by