Creating loop with two variables

조회 수: 4 (최근 30일)
Kevin P Meyer
Kevin P Meyer 2021년 8월 11일
댓글: Kevin P Meyer 2021년 8월 11일
Hello. I am trying to form a loop with two variables. Variable 1 which I call j = 1:12. Variable 2 which I call i = linspace(1,23,12). I am trying to create a cell named target{j} which has 12 different matrices of i:i+1. target{j} = i:i+1 , so that target{1} = 1:2, target{2} = 3:4, target{3} = 5:6, target{4} = 7:8, and so on.... Does anybody know how to do this? It would be great to get some help, thanks!

답변 (1개)

the cyclist
the cyclist 2021년 8월 11일
You only really need one loop:
target = cell(size(j))
target = 1×1 cell array
{0×0 double}
for j = 1:12
target{j} = [j j+1];
end
or zero loops:
j = num2cell(1:12);
target = cellfun(@(x)[x x+1],j,'UniformOutput',false)
target = 1×12 cell array
{[1 2]} {[2 3]} {[3 4]} {[4 5]} {[5 6]} {[6 7]} {[7 8]} {[8 9]} {[9 10]} {[10 11]} {[11 12]} {[12 13]}
  댓글 수: 1
Kevin P Meyer
Kevin P Meyer 2021년 8월 11일
Thank you for your answer. So, I need each cell to be {[1 2]} {[3 4}] {[5 6}], not {[1 2]} {[3 4]}. What I did:
k = linspace(1,23,12)
for j = 1:12
i = k(j)
target{j} = i: i+1
end
This code got me to what I needed. I appreciate your help!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by