How to create a new variable within each run in a for loop?
Mostrar comentarios más antiguos
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 comentarios
Scott MacKenzie
el 8 de Jul. de 2021
Editada: Scott MacKenzie
el 8 de Jul. de 2021
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
el 8 de Jul. de 2021
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
el 9 de Jul. de 2021
"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.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!