Can't get matrix to populate first column
이전 댓글 표시
So I'm trying to create a matrix that changes between 3 possible values based on modified values of a different matrix, here's the code:
edit: forgot to add cap and some ends
cap=15;
z=linspace(1,cap,cap)';
y=linspace(1,cap,cap)';
f=@(x,y) x-y;
M=f(z.',y);
p=zeros(size(M));
z1=z+1; %dem went to patch 1 and found food
z1(z1>cap)=cap;
for j=1:15
for k=1:15
if M(j,z1(k))>0
p(j,z1(k))=0.9;
elseif M(j,z1(k))<0
p(j,z1(k))=0.1;
else
p(j,z1(k))=0.5;
end
end
end
How do I get that first column to populate correctly?
I have multiple of these p matrices with different modifiers and some of them populate the entire matrix while others are missing a column or row
댓글 수: 5
Torsten
2024년 4월 20일
Your code cannot be executed. "cap"is undefined and your loop is not closed.
Torsten
2024년 4월 20일
z1(k) is always > 1, thus you get no entries in column 1 of M.
"How do I get that first column to populate correctly?"
Your code defines the values of z from 1. Then for z1 you add 1 to that, so the lowest z1 value (and column index) will be 2. But your code has no comments or explanation, so we cannot guess which of those operations is correct or incorrect.
Note: a simpler and more efficient approach for using CAP:
z1 = min(z1,cap);
Kitt
2024년 4월 20일
답변 (1개)
The smallest value in z is 1. Because you add 1 to z to generate z1, that means the smallest value in z1 is 2. You use z1 to determine which column of M and p to process, so you never process column 1.
But you could avoid the loops using the discretize function or by using the vectorized relational operators.
cap=15;
z=linspace(1,cap,cap)';
y=linspace(1,cap,cap)';
f=@(x,y) x-y;
M=f(z.',y)
% Define bins [-Inf, 0), [0, eps(0)), and [eps(0), Inf]
edges = [-Inf, 0 , eps(0) , Inf];
values = [ 0.1, 0.5, 0.9];
p = discretize(M, edges, values)
% or
p2 = repmat(0.5, size(M));
p2(M < 0) = 0.1;
p2(M > 0) = 0.9
check = isequal(p, p2)
카테고리
도움말 센터 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!