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

1 view (last 30 days)
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

Accepted Answer

dpb
dpb on 2 Dec 2021
Edited: dpb on 2 Dec 2021
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 Comment
tengteng QQ
tengteng QQ on 4 Dec 2021
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.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!