Change matrix elements in a loop?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
I am trying to figure out how to use a for loop to change the elements in a matrix.
I want to do this ten times.
For example, if row 1 of a 6x3 matrix is (a,a,0), I want to make a loop that generates row 2 as (2a,2a,0). I am basically trying to multiply the initial row to make all 6 rows increase by a multiple of a.
Thank you in advance for any suggestions!
채택된 답변
Star Strider
2015년 11월 6일
No loop necessary. Use bsxfun:
M = randi(9, 6, 3);
Mm = bsxfun(@times, M, [1:size(M,1)]')
This multiplies every row of ‘M’ by the column vector [1 2 ... 6]'.
댓글 수: 8
lsutiger1
2015년 11월 6일
Thank you for your response. This doesn't seem to be working, but I think that's because I left out an important piece of information as to why I need a loop: my matrix is actually 10x3x4. I have four different matrices that I need to do this to, and they all have different initial rows.
My pleasure.
That definitely does change your Question. Assuming that you want to do this for every one of the four ‘pages’ of your matrix, loop through them and do the multiplication on each with the loop:
M = randi(9, 10, 3, 4); % Create Matrix
Mm = zeros(size(M)); % Preallocate
for k1 = 1:size(M,3) % Iterate Over Pages
Mp = M(:,:,k1); % Select Page
Mm(:,:,k1) = bsxfun(@times, Mp, [1:size(Mp,1)]'); % Multiply Page
end
Mp % Last Page (Optional)
Mm(:,:,k1) % Multiplied Last Page (Optional)
The two ‘Optional’ lines simply verify that the code did what we want it to. They can be deleted.
Great, that helps a lot! Thank you! If I may ask one more question.. what would I do if I had a similar 10x3x4 matrix set-up, but it was all zeroes, except for the first row of each 'page.'
For example, if row 1 was (1,0,1), what would I need to do to make row 2 (2,0,2), row 3 (3,0,3), etc.?
I tried to do the following:
if ii=1:n
M = bxsfun(@times, X(:,:,ii), [1:size(X,1)]')
end
Star Strider
2015년 11월 6일
My pleasure!
It should work the same way, without modification. Anything multiplied by zero is zero, so the zeros would remain and only the non-zero values would change.
I assume you define ‘n’ in your loop as size(X,3).
The error that I am getting says:
Error using bsxfun Non-singleton dimensions of the two input arrays must match each other
Here is my entire code thus far; maybe this will help.
% Create matricies for atomic coordinates in unit cell
a = input('What is the lattice constant? \n a = ');
n = input('How many molecular orientations are required? \n n = ');
d = input('How many unit cells in each direction are desired? \n d = ');
type(:,:,n) = zeros(d*a,3);
% Generate initial molecular positions in unit cell
for ii=1:n
disp(['What is the position of molecule ' num2str(ii) ' in terms of a?']);
x = input('x-direction: ');
type(1,1,ii) = x;
y = input('y-direction: ');
type(1,2,ii) = y;
z = input('z-direction: ');
type(1,3,ii) = z;
end
% Generate lattic from initial molecular positions
for ii=1:d % create 10 unit cells in each direction
lattice = bsxfun(@times, type(:,:,ii), [1:size(type,3)]');
end
You changed my code! You’re not creating the vector along the correct dimension.
Use this instead:
lattice = bsxfun(@times, type(:,:,ii), [1:size(type,1)]');
Use the row size (dimension 1) not the page size (dimension 3). That’s why it’s not working. Changing it back to my original code works.
lsutiger1
2015년 11월 6일
Yes, I changed it because I was getting that error; neither the 1 or 3 seems to make a difference. This is why I am confused.
Star Strider
2015년 11월 6일
I can’t run your code because I have no idea what you are doing and the inputs should be. Please attach a .mat file with the appropriate size and values for ‘type’. Use the ‘paperclip’ icon, and complete both the ‘Choose file’ and ‘Attach file’ steps.
My code does what you want it to, as you requested, but I can’t troubleshoot it with your code without the appropriate data.
추가 답변 (0개)
카테고리
도움말 센터 및 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!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
