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
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
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
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
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!