How to create a new variable within each run in a for loop?
古いコメントを表示
For an assignment of mine, I am using a for loop to obtain a new matrix "A" for each number within an "x" range.
However, every time the loop runs, the variable A remains unchanged, and so this would make it difficult to distinguish
the matrix with different numbers of "x". Is there a way where each time the loop runs, I can set a new variable equal to "A" continuously?
So then I would get A1, A2, A3, A4, A5...etc. I would appreciate any help!
clc
clear all
%define variables
x=0:0.01:2;
for k=1:length(x) %x as a range
alpha=atan(1./(2-x(k))); %alpha angle
beta=atan((2-x(k))./1); %beta angle
gamma=atan(x(k)); %gamma angle
A=zeros(10); % setting up zero matrices
b=[0;2;0;1;0;0;0;0;0;0]; % for later substitution
%Define the A matrix
A(1,1:2)=[-1, cos(alpha)];
A(2,2)=[sin(alpha)];
A(3,1:5)=[1,0,0,0,-1];
A(4,3)=[-1];
A(5,2:7)=[sin(beta),0,0,0,sin(gamma),-1];
A(6,2:5)=[-cos(beta),-1,0,-cos(gamma)];
A(7,6:8)=[1,0,-1];
A(8,7:9)=[-1,0,1];
A(9,4:10)=[1,sin(gamma),0,0,0,0,-1];
A(10,5:7)=[cos(gamma),0,1];
A
xrow=pinv(A)*b %gaussian method for finding unknown forces
end
4 件のコメント
Scott MacKenzie
2021 年 7 月 8 日
編集済み: Scott MacKenzie
2021 年 7 月 8 日
What your are describing amounts to poor programming and poor use of MATLAB's capabilities. Visit this TUTORIAL for complete details. The variables you are describing can probably just be rows or columns in a matrix that is built up in the loop -- or something. Post some code and we'll have a look.
dpb
2021 年 7 月 8 日
As Scott says, "there be dragons!" in that approach and you do NOT want to go down that path. Stephen C will probably come along shortly and reinforce the message even more strongly! :)
Another alternative, depending upon the content of A each pass is to use cell array -- but as above "show us code"; we can't guess what you're really trying to do so don't know best solution.
Jason Wang
2021 年 7 月 9 日
"However, every time the loop runs, the variable A remains unchanged"
Because you have not used any indexing based on the loop iteration variable k to store the results of each loop. How to use indexing in a loop is shown in the introductory tutorials, or the documentation on array preallocation:
"Is there a way where each time the loop runs, I can set a new variable equal to "A" continuously?"
Of course, this is easy with basic MATLAB indexing.
"So then I would get A1, A2, A3, A4, A5...etc."
That would be about the worst approach.
Rather than forcing pseudo-indices into variable names, just use actual indices in to one array.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!