MATLAB Matlab and preparing matrix lines

AI Thread Summary
To create a matrix qx in MATLAB where each row corresponds to a value in the vector U, the discussion suggests avoiding a for loop by using matrix operations. By creating an intermediate matrix U2, which replicates U across columns, and a matrix Y2 that replicates the ky vector across rows, the dimensions can be aligned for element-wise operations. This approach allows the function to reference the same index in both matrices, effectively generating the desired qx matrix. While this method is efficient for reasonably sized problems, there may be alternative techniques that could optimize storage space further.
hokhani
Messages
556
Reaction score
17
In the Matlab program below

U=[210; 100; 150]
ky= linspace(-.2,.2);
qx=sqrt(((150-U)/.2)^2-ky.^2)

I want to have qx as a matrix in which each row is corresponding to one value of U: the first row corresponds to 210, the second to 100 and ... How should I do this? (I want to avoid the "for loop" if possible).
 
Physics news on Phys.org
One way would be to make intermediate matrices so that the dimensions agree.
U2 = U * ones(1,100);
Y2 = ones(3,1)*ky;
Then your function will be referring to the same index in both reference matrix.
There might be a better way that is more effecient with your storage space, but for reasonably sized problems, this would do the trick.
 
  • Like
Likes hokhani

Similar threads

Back
Top