Building a 2x2 Matrix with one for-loop

5 Ansichten (letzte 30 Tage)
Florian
Florian am 25 Sep. 2013
Beantwortet: Florian am 26 Sep. 2013
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.)

Akzeptierte Antwort

Image Analyst
Image Analyst am 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

Weitere Antworten (1)

Florian
Florian am 26 Sep. 2013
thank you very much !! it works. and also thanks for the advice. I will change my loop counters in future :)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by