Using for-loop to extract data from every column in a matrix
이전 댓글 표시
Hi,
I'm new to using for-loops - can anyone help with my problem.
I have a matrix, 18000X31. I want to be able to write a for loop that for each column, a new variable is created that includes the data from the rows 3000-13600. Any help would be gratefully appreciated.
Thanks in advance!
댓글 수: 5
"I have a matrix, 18000X31."
So you have a matrix, the basic data format for easily storing and efficiently processing data within MATLAB (in fact even the name comes from "MATrix LABoratory", giving a big hint that using matrices is probably a very good idea).
"I want to be able to write a for loop that for each column, a new variable is created that includes the data from the rows 3000-13600."
So you want to replace your simple matrix (which is trivial and efficient to access using indexing) with a whole bunch of dynamically created variables, thus making accessing your data slow, complex, inefficient, obfuscated, and difficult to debug.
Why would you want to do that?
"Any help would be gratefully appreciated."
Explain what you are actually trying to achieve (not how you think you might achieve it).
Edward Keavney
2022년 5월 30일
Walter Roberson
2022년 5월 30일
mean100 = reshape(mean(reshape(M(3000:13599, :), 100, [], size(M,2)), 1), [], size(M,2));
Watch out for that endpoint !
Edward Keavney
2022년 5월 30일
Stephen23
2022년 5월 30일
"I thought using a for-loop would help to allow me to step-by-step work through my problem."
There is no problem with using a FOR loop. Or reshaping, as Walter Roberson showed you.
But you should avoid creating "new variables" as you described in your question.
답변 (2개)
M = randi([0 9], 180, 31); %example
letters = ['A':'Z' 'a' : 'z'];
numletters = length(letters);
for col = 1 : size(M, 2)
randname = letters( randi(numletters, 1, 32) );
tosave.(randname) = M(:,col);
end
tname = tempname() + ".mat";
save(tname, '-struct', 'tosave');
load(tname)
whos
Now what? What are you going to do with sReqMWIVCMwWweFeFOJCcijOdpnHeNHi now that you have it?
Image Analyst
2022년 5월 30일
@Edward Keavney, do this for your matrix m:
[rows, columns] = size(m)
for col = 1 : columns
fprintf('Processing column %d of %d.\n', col, columns);
% Create a new variable with only this particular column,
% but only with rows 3000 to 13600:
thisColumn = m(3000 : 13600, col);
% Now process this column somehow,
% like getting its mean or whatever you want to do.
end
fprintf('All done!\n');
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!