- Don't use line as a variable, it's a builtin important plotting function,
- size(A) returns a 2-vector, iterating over it is not what you want here, you want only number of columns in A
- While not fatal, you didn't preallocate the output array final which is inefficient altho for such small array won't be noticeable.
for loop question, how to put the for loop answer in new matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
dpb
2021년 12월 2일
편집: dpb
2021년 12월 2일
A number of issues with the above code --
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!