2 different for loops at the same time ?
1 次查看(过去 30 天)
显示 更早的评论
Hi, I've just tried to make 2 for loops at the same time but I couldn't achieve that properly. Assume that "A" can be any matrix. I upload example.xlsx file as an .txt file.
A = xlsread('example.xlsx');
for ii= 5:5:length(A);
for jj= 4:5:length(A);
M=A(ii,11)*(10^A(jj,1))
end
end
When I try this code I get 16 M as an answer, I want to take 4 answers. Does anybody have any clue that can help ?
0 个评论
采纳的回答
Walter Roberson
2018-5-19
A = xlsread('example.xlsx');
iivals = 5:5:length(A);
jjvals = 4:5:length(A);
numii = length(iivals);
numjj = length(jjvals);
M = zeros(numii, numjj);
for ii_idx = 1 : numii
ii = iivals(ii_idx);
for jj_idx = 1 : numjj
jj = jjvals(jj_idx);
M(ii_idx, jj_idx) = A(ii,11)*(10^A(jj,1))
end
end
3 个评论
Walter Roberson
2018-5-19
A = xlsread('example.xlsx');
for ii= 5:5:length(A);
M( ii/5 ) = A(ii,11) * (10^A(ii-1,1))
end
更多回答(3 个)
Majid Farzaneh
2018-5-19
编辑:Majid Farzaneh
2018-5-19
Hi, It's better use size(A,1) [for number of rows] or size(A,2) [for number of columns] instead of length(A). Because it's may not exactly what you want. At the M=A(ii,11)*(10^A(jj,1)) if you want to multiply values element by element you should use '.*' instead of '*'.
for ii= 5:5:size(A,1);
for jj= 4:5:size(A,1);
M=A(ii,11).*(10^A(jj,1))
end
end
Rik
2018-5-19
You must index M.
jj_= 4:5:length(A);
ii_= 5:5:length(A);
A = xlsread('example.xlsx');
M=zeros(numel(ii),numel(jj));%pre-allocate
for ii=1:numel(ii_)
for jj=1:numel(jj_)
M(ii,jj)=A(ii_(ii),11)*(10^A(jj_(jj),1));
end
end
0 个评论
Ameer Hamza
2018-5-19
编辑:Ameer Hamza
2018-5-19
You don't need a for loop. Replace it with this:
M = A(5:5:length(A), 11).*10.^(A(4:5:length(A), 1));
This will work in R2016b and later.
4 个评论
Ameer Hamza
2018-5-19
As you can see, that your final answer is the first column of of 4x4 matrix. So you can get it like this
M = A(5:5:length(A), 11)*10.^(A(4:5:length(A), 1))';
M = M(:,1);
It will give you your required 4 numbers
另请参阅
类别
在 Help Center 和 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!