How to create vectors in the for loop

조회 수: 3 (최근 30일)
Yerzhigit Bapin
Yerzhigit Bapin 2017년 7월 13일
편집: Andrei Bobrov 2017년 7월 14일
I have a hard time understanding the logic behind the for loops, so here is the question:
I have a vector:
A = [5 8 1 4 9 2];
for each value of A, I need to create other vectors in the format B = linspace(-A,A,47), so the output looks as follows:
B(1) = -5 -4.78 -4.56 ... 4.56 4.78 5
B(2) = -8 -7.65 - 7.3 ... 7.3 7.65 8
.
.
.
B(6) = -2 -1.91 -1.83 ... 1.83 1.91 2
Thank you!

채택된 답변

Elias Gule
Elias Gule 2017년 7월 13일
Try this.
B = arrayfun(@(x) linspace(-x,x,47),A,'uni',false); % B is a cell array of vectors
Using a for loop:
len = length(A);
B = cell(len,1);
for index = 1 : len
B{index} = linspace(-A(index),A(index),47);
end
  댓글 수: 1
Yerzhigit Bapin
Yerzhigit Bapin 2017년 7월 14일
Thanks, this works, but is there a way to do it in a matrix rather than cell? I guess nested for loop will be required for that?

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 7월 13일
편집: Andrei Bobrov 2017년 7월 14일
n = 47;
nn = n - 1;
B = A(:)*2/nn*(0:nn) - A(:); % R2016b or later
B = bsxfun(@minus,A(:)*2/nn*(0:nn),A(:)); % R2016a or earlier
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2017년 7월 14일
편집: Andrei Bobrov 2017년 7월 14일
I'm fixed (2).

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by