for loop question, how to put the for loop answer in new matrix

조회 수: 1 (최근 30일)
tengteng QQ
tengteng QQ 2021년 12월 2일
댓글: tengteng QQ 2021년 12월 4일
Dear all, I got some problems with my code. I suppose it is basic. However, I can't find where is the problem. I want to find a position in my matrix. First, I would like to find out the number>=9 positions for each column. When I get the position, I would like to get the nearest one and the far one. And I use k=x1-x2, so I can get the distances for each column. if none of the numbers can fit into the statement( x1-x2 empty vector), then skip. In the end, I want to put the information into a new matrix called 'final'. Thank you for your help!
A = [88,2,77,4,5;6,2,9,5,0;6,7,3,4,5;6,7,8,5,6;7,8,9,10,6;7,8,9,99,15;45,55,2,2,2;67,66,56,87,1];
for j = 1:size(A)
line=A(j,:);
C=find(line>=9);
x1=max(C);
x2=min(C);
k=x1-x2
final(j,:)=k
end

채택된 답변

dpb
dpb 2021년 12월 2일
편집: dpb 2021년 12월 2일
A number of issues with the above code --
  1. Don't use line as a variable, it's a builtin important plotting function,
  2. size(A) returns a 2-vector, iterating over it is not what you want here, you want only number of columns in A
  3. While not fatal, you didn't preallocate the output array final which is inefficient altho for such small array won't be noticeable.
Try something more like
nC=size(A,2); % number columns in A
magicNo=9; % make variable; don't bury in code so can change easily
res=nan(nC,1); % output vector preallocation
for c=1:nC % iterate over columns
C=find(A(:,c)>=magicNo); % get vector of locations
if isempty(C), continue, end % skip if none found, leaves output NaN
res(c)=range(C); % save the range of found locations
end
  댓글 수: 1
tengteng QQ
tengteng QQ 2021년 12월 4일
Sorry for replying late. I really appreciate your help.
Though, may I ask you how can I begin to learn coding in Matlab. I am a real beginner and seems my coding is not appropriate? (like it is not a good idea in your view). And I am feeling so struggle when I have an idea but it is not connected with my coding skill.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by