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

1 回表示 (過去 30 日間)
Ashi Khajotia
Ashi Khajotia 2023 年 4 月 19 日
編集済み: chicken vector 2023 年 4 月 19 日
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
  3 件のコメント
chicken vector
chicken vector 2023 年 4 月 19 日
編集済み: chicken vector 2023 年 4 月 19 日
d1 = 0.1077;
lam = 3:0.1:7;
th = 0;
n1 = 2.32;
phi1 = 2*pi.*(d1./lam).*sqrt((n1).^2 - sind(th).^2);
P1 = zeros(2,2,length(lam));
P1(1,1,:) = exp(1i.*phi1);
P1(2,2,:) = exp(-1i.*phi1)];
This is just one of the many ways you could build your matrix.
Other methods may involve the use of reshape.
Note that the for loop changes the values of the variable j, which your are not using so it is completely useless.
At each iteration you overwrite the variable P1 with the same values since:
x = 1:3;
M = [x 0; 0 x];
Produces:
M = [1 2 3 0 ; 0 1 2 3];
To effectively use the loop I suggest you to initialise the variable outside the loop and use j to change indexing inside P1.
P1 = zeros(2,2,length(lam));
phi1 =2*pi.*(d1./lam).*sqrt((n1).^2 - sind(th).^2);
for j = 1 : length(lam)
P1(:,:,j) = [exp(1i.*phi1(j)) 0 ; 0 exp(1i.*phi1(j))];
end
Anyway I don't reccomend you doing this because vectorisation is much faster than looping and you would notice a great difference with large datasets.
Ashi Khajotia
Ashi Khajotia 2023 年 4 月 19 日
Let us suppose lam has only one value, then P1 is a 2x2 matrix. but as I want to change lam, phi1 will change and correspondingly I want P1 to be changed with each iteration. I hope I am clear now.

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

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 4 月 19 日
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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by