Nested For Loops help

조회 수: 6 (최근 30일)
Ife M
Ife M 2018년 2월 25일
답변: Fahad HCT2021 2020년 4월 5일
Hello!
I am attempting to use a nested for loop on two columns of data. Here's an example of what I am trying to accomplish
A = [1;2;3;4]
B = [4;3;2;1]
for i = 1:numel(A)
for j = 1: numel(B)
diff = A(i) - B(j)
end
end
I want the output to be [(1-4) (2-4) (3-4) (4-4) (1-3) (2-3) (3-3) (4-3) etc] where it iterates through the A matrix completely but selects the same value from the B matrix each time. Essentially: A(1)-B(1), A(2)-B(1), A(3)-B(1), A(4)-B(1) and have an output matrix that contains all of the iteration outputs. So it should be a 16x1 matrix Any advice on what I am doing wrong?
  댓글 수: 1
Stephen23
Stephen23 2018년 2월 26일
편집: Stephen23 2018년 2월 26일
DO NOT use diff as a variable name!
Because then the inbuilt (and very useful) function diff will not work!
Always check if a variable name is used:
which diff

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

채택된 답변

David Fletcher
David Fletcher 2018년 2월 25일
You're not retaining the variable 'diff' but just keep replacing it with the latest subtraction. You could initialize diff=[] before the loops and then change the assignment to diff=[diff A(i)-B(j)]. Computationally, it's not great, but it should do the job.
  댓글 수: 1
Ife M
Ife M 2018년 2월 25일
Thank you so much!!

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

추가 답변 (1개)

Fahad HCT2021
Fahad HCT2021 2020년 4월 5일
% Define variables
syms ;
f=@(i) ;
% Loop to create vector df1
for i= ;
deriv=diff( ); % Find the general ith derivative of f
df1(i)=subs( ); % Substitute x=1
end; % DO NOT CHANGE CODE ON THIS LINE
df1 % Display the vector df1

카테고리

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