How can i create a for loop that modifies a column in an existing matrix?
조회 수: 1 (최근 30일)
이전 댓글 표시
Tore Henriksen Eliassen
2020년 9월 22일
댓글: Tore Henriksen Eliassen
2020년 9월 22일
So i want to make a for loop that takes the startmatrix(given under):
dicevalue = [1,2,3,4,5,6]';
zeroes = [0,0,0,0,0,0]';
startmatrix = [dicevalue,zeroes];
Startmatrix =
1 0
2 0
3 0
4 0
5 0
6 0
Then replaces the zeroes with the values from amount(given under) according to the values from throwvalues(given under)
throw = [1,1,3,4,5,1];
throwvalues = unique(throw)';
amount = histc(throw(:),throwvalues);
throwmatrix = [throwvalues,amount];
Throwmatrix =
1 3
3 1
4 1
5 1
My overall hope is that i somehow can make a matrix that combines the values from 1 to 6 with the values from my amount variable to in the end get something like this:
Finishedmatrix =
1 3
2 0
3 1
4 1
5 1
6 0
Thankful for all help i can get :)
댓글 수: 0
채택된 답변
the cyclist
2020년 9월 22일
A = [1,1,3,4,5,1];
dicevalue = [1,2,3,4,5,6]';
throwCounts = histcounts(A,[dicevalue; Inf])';
output = [dicevalue, throwCounts];
댓글 수: 3
the cyclist
2020년 9월 22일
I am wary of the use of the phrase, "any unknown A". I mean, it will not work if someone enters the cell array {'x','y','zebra'}.
But it should work for a row vector of any length that contain values 1:6.
This is your code, so you're the one who needs to reach a level of understanding of the histcounts function that makes you confident it does what you need. Beware of blindly using code from the internet that you've not made an effort to understand.
추가 답변 (1개)
Ameer Hamza
2020년 9월 22일
편집: Ameer Hamza
2020년 9월 22일
If startmatrix and throwmatrix follow the same pattern as you gave in the question, i.e., the first columns of both matrices are always in increasing order, then you can do something like this.
A = [1,1,3,4,5,1];
dicevalue = [1,2,3,4,5,6]';
zeroes = [0,0,0,0,0,0]';
startmatrix = [dicevalue,zeroes];
throwmatrix = [1 3; 3 1; 4 1; 5 1];
idx = ismember(startmatrix(:,1), throwmatrix(:,1));
startmatrix(idx, 2) = throwmatrix(:, 2);
Result
>> startmatrix
startmatrix =
1 3
2 0
3 1
4 1
5 1
6 0
Alternative solution:
A = [1,1,3,4,5,1];
dicevalue = [1,2,3,4,5,6]';
zeroes = [0,0,0,0,0,0]';
startmatrix = [dicevalue,zeroes];
throwmatrix = [1 3; 3 1; 4 1; 5 1];
startmatrix(throwmatrix(:,1), 2) = throwmatrix(:,2);
댓글 수: 4
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!