Help with jumping one position using circshift function in a for loop
Afficher commentaires plus anciens
Hi there,
I am trying to create a transformation matrix for the matrix stiffness method, and to save time I am using the circshift function in a for loop.
So, I am starting off with this
n = 12;
T = zeros(2,n);
T(1,1) = 1;
T(2,2) = 1
for i = 1:9
Tn(:,:,i) = circshift(T,[0,i])
end
However, every 3rd interation I want the values (the 1's) to shift one extra place to the right. So I want the Tn matrix to follow this pattern:
Tn = [1 1 0 1 1 0 1 1 0 1 1 0;
0 1 1 0 1 1 0 1 1 0 1 1]
I guessed at trying this:
for i = 1:9
Tn(:,:,i) = circshift(T,[0,i])
if i == 3,6,9
Tn(:,:,i) = circshift(T,[0,i+1])
endif
end
But it didn't work.
I hope I have explained this clearly. Can somebody help please?
Many thanks.
1 commentaire
Chhayank Srivastava
le 15 Août 2023
Could you clarify what do you mean when you say you want Tn to follow that pattern, does that mean after running the loop Tn should look like that?
Réponse acceptée
Plus de réponses (3)
n = 12;
T = zeros(2,n);
T(1,1) = 1;
T(2,2) = 1
Here's one way to generate that Tn from this T using circshift in a loop:
Tn = zeros(2,n,8);
shift = 0;
for i = 1:size(Tn,3)
if mod(i,2) == 1
shift = shift+1;
end
Tn(:,:,i) = circshift(T,[0,shift-1]);
shift = shift+1;
end
disp(Tn);
Hi,
I see some issue with the if statement mentioned above.
So just fixing the if statement
n = 12;
T = zeros(2,n);
T(1,1) = 1;
T(2,2) = 1;
for i = 1:9
Tn(:,:,i) = circshift(T,[0,i]);
if mod(i,3) == 0
Tn(:,:,i) = circshift(T,[0,i+1]);
end
end
Tn
Moreover, I am assuming after running the program you want the Tn to look like
Tn = [1 1 0 1 1 0 1 1 0 1 1 0;
0 1 1 0 1 1 0 1 1 0 1 1];
But in the above code you are generating a 3D matrix.
A simpler solution would be just to use repmat and transformation matrix
T = [1,1,0;0,1,1];
Tn = repmat(T,1,4)
But, going by your method
clear;clc;
n = 12;
T = zeros(2,n);
T(1,1) = 1;
T(2,2) = 1;
for i = 1:9
if mod(i,2) == 0
T = circshift(T,[0,2]);
Tn(:,:,i) = T;
else
T = circshift(T,[0,1]);
Tn(:,:,i) = T;
end
end
Tn = Tn(:,:,1)+Tn(:,:,2)+Tn(:,:,3)+Tn(:,:,4)+Tn(:,:,5)+Tn(:,:,6)+Tn(:,:,7)+Tn(:,:,8)
Scott Banks
le 15 Août 2023
5 commentaires
Star Strider
le 15 Août 2023
@Scott Banks — Thank you!
Scott Banks
le 17 Août 2023
Star Strider
le 17 Août 2023
@Scott Banks — Thank you!
Voss
le 17 Août 2023
@Scott Banks: I'm a little confused because if Tn(:,:,3) and T(n:,:,4) are both shifted to the right, then they are still the same as each other, which contradicts your statement that they should not be the same as each other.
Can you just write down the complete 3D array as it should be?
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!