Want to insert a matrix in a for loop and change it with a variable

Ashi Khajotia · Apr 20, 2023 · 1.9K views
Question
Hello,   So, I have a variable phi(1x41) changing with lambda(1x41) and there is matrix (2x2) inside a for loop that needs to be changed with phi but the dimension of matrix should be (2x2x41) instead of (2x42) as it shown in workspace. Can anyone help me in this?   d1 = 0.1077; lam = 3:0.1:7; th = 0; n1 = 2.32; for j = 1:length(lam) phi1 =2*pi.*(d1./lam).*sqrt((n1).^2 - sind(th).^2); P1 = [exp(1i.*phi1) 0; 0 exp(-1i.*phi1)]; end  
Expert Answer
Profile picture of Prashant Kumar
Prashant Kumar PhD Expert
Answered Aug 25, 2026
d1 = 0.1077;
lam = 3:0.1:7;
th = 0;
n1 = 2.32;

%Define phi1 outside the loop as it is not varying with the loop
phi1 = 2*pi.*(d1./lam).*sqrt((n1).^2 - sind(th).^2);
numlam = numel(lam);
%Preallocation
P1 = zeros(2,2,numlam);

for j = 1 : numlam
   P1(:,:,j) = [exp(1i.*phi1(j)) 0; 0 exp(1i.*phi1(j))];
end

 

100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!