Building a 2x2 Matrix with one for-loop
5 views (last 30 days)
Show older comments
A friendly hello :)
I actually got a simple question. Looking at the folling code:
k=1;
for i= 1:4
M(k,:)=i+[2 3 4];
k=k+1;
end
This will create a 4x3 Matrix looking like:
M =
3 4 5
4 5 6
5 6 7
6 7 8
So, but without doing " M' " (transpose) at the end, how can I switch rows and columns?? In other words: I tried this:
M(:,k)=i+[2 3 4];
So that the Matrix builds up column-wise into a 3x4 Matrix. but it doesn't work. why??
Kind regards
ps: only for interests: I got the problem from this. I try to compare one list of words, with one other.
k=1;
for i=1:100000
test(k,:)=strncmp(words(i),word_list,3);
k=k+1;
end
naturally " strncmp(words{s(i)},word_list,3) " gives a column-vector, because my word_list is a column (imported from a text file). but here, each result of "strncmp" lines up in a row. my problem is: it is just very confusing !
test(:,k)=strncmp(words(i),word_list,3); %does not work
(again, I could just transpose at the end, but this transposing takes noticely the longest time. that's why I removed it and I am curious, if there is no way in already building up the Matrix the correct way. or the way I want.)
0 Comments
Accepted Answer
Image Analyst
on 25 Sep 2013
Try this:
% First way:
for k= 1:4
M(k,:)=k+[2 3 4];
end
M
% Second way:
clear('M'); % Need to clear it if in the same script.
for k= 1:4
M(:,k)=k+[2; 3; 4];
end
M
You don't need the k counter. And it's also bad practice to use i (the imaginary variable) as a loop counter so I switched it to k. Your other problem was not having semicolons in the vector to make sure it was a column vector instead of a row vector . The result:
M =
3 4 5
4 5 6
5 6 7
6 7 8
M =
3 4 5 6
4 5 6 7
5 6 7 8
0 Comments
More Answers (1)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!