Hey
I have a loop an I'm trying to create some unit vectors as follows:
e1 = [1;0;0;0;0;0;0;0]
e2 = [0;1;0;0;0;0;0;0]
e3 = [0;0;1;0;0;0;0;0]
all the way to
e7 = [0;0;0;0;0;0;0;1]
Thanks

댓글 수: 1

James Tursa
James Tursa 2020년 2월 3일
1) Do you have to use a loop? Is that part of the assignment? There are easier ways to do this other than a loop.
2) You should not use e1 ... e7 as the variable names. This will create problems downstream in your code. I would suggest a cell array instead, e{1}, e{2}, ... , e{7}. This will make it easier to use indexing on these variables. E.g.,

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

 채택된 답변

Shunichi Kusano
Shunichi Kusano 2020년 2월 3일

0 개 추천

Hi azarang,
The following code is an example
vecLength = 8;
I = eye(vecLength);
for i = 1:vecLength
% save the vector as a field of the struct
fieldname = ['e' num2str(i)];
unitVectors.(fieldname) = I(:,i);
end
HTH

추가 답변 (1개)

James Tursa
James Tursa 2020년 2월 4일

1 개 추천

Since a complete answer has already been posted, I will post this one using a cell array result which will be much easier to index:
n = whatever length vectors you want
e = mat2cell(eye(n),ones(n,1),n);

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 2월 3일

답변:

2020년 2월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by