- 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 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
dpb
le 2 Déc 2021
Modifié(e) : dpb
le 2 Déc 2021
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!