array manipulation in loop through a sequence

3 次查看(过去 30 天)
Dear programmers
I have defined an array of 4 values with 1 in all the rows initially as : tissue = [1 1 1 1]
After 1st iteration, I want to replace '1' at 4th position by '2' as: [1 1 1 2].
After 2nd iteration, '2' wil be shifted to 3rd position and new value '3' will take the 4th position as: [1 1 2 3 ] .
After 3rd iteration, '2' wil be shifted to 2nd position ,'3' wil be shifted to 3rd position and new value '4' will take the 4th position as: [1 2 3 4].
After 4th iteration, '2' wil be shifted to 1st position ,'3' wil be shifted to 2nd position, '4' wil be shifted to 3rd position and new value '5' will take the 4th position as: [2 3 4 5].
In the below code even if I am being asked the iteration number but I am getting the results only for the i=4. Where am I doing the error ? Please help!
E = zeros(1,4);
for i=1:4
E(i) = 1
end
prompt = 'What is the iteration number? ';
i = input(prompt)
for i=1:4
E(5-i)= 2
for i=2:4
E(6-i)= 3
for i=3:4
E(7-i)= 4
for i=4
E(4)=5
end
end
end
end
  1 个评论
Walter Roberson
Walter Roberson 2019-9-2
i = input(prompt)
assigns a particular value to i according to the user's input
for i=1:4
then overwrites i with the value 1, then 2, then 3, then 4.

请先登录,再进行评论。

采纳的回答

Andrei Bobrov
Andrei Bobrov 2019-9-2
E = ones(4);
n = size(E,1);
for ii = 1:n
E(ii,n-ii+1:n) = E(ii - 1 + (ii == 1),n-ii+1:n) + 1
end
  3 个评论
Andrei Bobrov
Andrei Bobrov 2019-9-5
E = ones(1,4);
A = zeros(4);
for ii = 1:4
E(end - ii + 1 : end) = E(end - ii + 1 : end) + 1
A(ii,:) = E;
end
RAJ
RAJ 2019-9-5
Thanks Mr. Andrei your kind help and sorry for bothering you again .
It is almost done. But in the problem if the values are not incremented by 1 as in this case 2,3,4 and 5 but rather the values are random say 20,300.5,60 and 1.5. In that case the code is not working because in actual problem that I am working on, the values of E at 4th position can be anything and those will be read from a text file(in which the first column will be for an element and 2nd column is the E value that will take the position of E4 everytime and replace the previously positioned E4 to E3 i.e push one position ahead).
N.B: I am attaching the text file herewith. In the text file the 1st column is the finite element number and the 2nd column corresponds to the respective E that will take the place of E4. Such text files will be read in every iteration of the main program. I have tried to make a separate function by do loop to retrieve those E values row wise but that is not working.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by