eqn =
主要内容
Results for
ere's a single MATLAB script addressing all the problems described:
matlab
% Problem 1: Simple if Statement
x = 5; % Example value
if x > 0
disp('The number is positive.');
end
% Problem 2: if ... else Statement
x = 7; % Example value
if mod(x, 2) == 0
disp('The number is even.');
else
disp('The number is odd.');
end
% Problem 3: if ... elseif ... else Statement
score = 85; % Example value
if score >= 90 && score <= 100
disp('Grade A');
elseif score >= 80 && score < 90
disp('Grade B');
elseif score >= 70 && score < 80
disp('Grade C');
elseif score >= 60 && score < 70
disp('Grade D');
else
disp('Grade F');
end
% Problem 4: Nested if Statement
x = 8; % Example value
if x > 0
if mod(x, 2) == 0
disp('The number is positive and even.');
else
disp('The number is positive and odd.');
end
end
% Problem 5: Temperature Classification (if ... elseif)
T = 18; % Example value
if T < 0
disp('Freezing');
elseif T >= 0 && T <= 15
disp('Cold');
elseif T >= 16 && T <= 25
disp('Mild');
else
disp('Hot');
end
% Problem 6: Simple switch Statement
grade = 'B'; % Example value
switch grade
case 'A'
disp('Excellent');
case 'B'
disp('Good');
case 'C'
disp('Fair');
case 'D'
disp('Poor');
case 'F'
disp('Fail');
otherwise
disp('Invalid grade.');
end
% Problem 7: Nested switch Statement
department = 'Engineering'; % Example value
major = 'Mechanical'; % Example value
switch department
case 'Engineering'
switch major
case 'Electrical'
disp('Electrical Engineering');
case 'Mechanical'
disp('Mechanical Engineering');
case 'Civil'
disp('Civil Engineering');
otherwise
disp('Unknown major.');
end
case 'Arts'
disp('Arts Department');
case 'Sciences'
disp('Sciences Department');
otherwise
disp('Unknown department.');
end
% Problem 8: Leap Year Check (if Statements)
year = 2024; % Example value
if mod(year, 4) == 0
if mod(year, 100) ~= 0 || mod(year, 400) == 0
disp('Leap year');
else
disp('Not a leap year');
end
else
disp('Not a leap year');
end
% Problem 9: Triangle Type (if ... elseif)
a = 5; b = 5; c = 5; % Example values
if a == b && b == c
disp('Equilateral triangle');
elseif a == b || b == c || a == c
disp('Isosceles triangle');
else
disp('Scalene triangle');
end
% Problem 10: Calculator with switch Statement
num1 = 10; % Example value
num2 = 5; % Example value
operation = '*'; % Example value
switch operation
case '+'
result = num1 + num2;
disp(['Result: ', num2str(result)]);
case '-'
result = num1 - num2;
disp(['Result: ', num2str(result)]);
case '*'
result = num1 * num2;
disp(['Result: ', num2str(result)]);
case '/'
if num2 ~= 0
result = num1 / num2;
disp(['Result: ', num2str(result)]);
else
disp('Error: Division by zero');
end
otherwise
disp('Invalid operation');
end
This code covers all the problems mentioned in your document. Replace the example values with inputs as needed.
% MATLAB Homework Solutions
% Problem 1: Sum of Even Numbers using while Loop
sum_even = 0;
num = 1;
while num <= 50
if mod(num, 2) == 0
sum_even = sum_even + num;
end
num = num + 1;
end
disp('Problem 1: Sum of Even Numbers');
disp(sum_even);
% Problem 2: Factorial Calculation using for Loop
n = 5; % Example number to calculate factorial
factorial_result = 1;
for i = 1:n
factorial_result = factorial_result * i;
end
disp('Problem 2: Factorial of the number');
disp(factorial_result);
% Problem 3: Multiplication Table using Nested Loops
disp('Problem 3: 10x10 Multiplication Table');
for i = 1:10
for j = 1:10
fprintf('%d\t', i * j);
end
fprintf('\n');
end
% Problem 4: Count Digits using while Loop
number = 12345; % Example number
digit_count = 0;
while number > 0
number = floor(number / 10);
digit_count = digit_count + 1;
end
disp('Problem 4: Number of digits');
disp(digit_count);
% Problem 5: Skip Multiples of 3 using for Loop and continue
disp('Problem 5: Numbers from 1 to 20 (skipping multiples of 3)');
for i = 1:20
if mod(i, 3) == 0
continue;
end
disp(i);
end
% Problem 6: Break a while Loop when Condition is Met
num = 101; % Start checking from 101
while true
if mod(num, 5) == 0 && mod(num, 7) == 0
disp('Problem 6: First number greater than 100 divisible by 5 and 7');
disp(num);
break;
end
num = num + 1;
end
% Problem 7: Summing Diagonal Elements using Nested Loops
matrix = randi([1, 20], 5, 5); % Create a 5x5 random matrix
diagonal_sum = 0;
for i = 1:5
diagonal_sum = diagonal_sum + matrix(i, i);
end
disp('Problem 7: Sum of diagonal elements');
disp(matrix); % Display the matrix
disp(diagonal_sum);
% Problem 8: Reverse a Number using while Loop
num = 12345; % Example number
reversed = 0;
while num > 0
remainder = mod(num, 10);
reversed = reversed * 10 + remainder;
num = floor(num / 10);
end
disp('Problem 8: Reversed number');
disp(reversed);
% Problem 9: Prime Number Checker using for Loop and break
num = 29; % Example number to check
is_prime = true; % Assume the number is prime
if num < 2
is_prime = false;
else
for i = 2:sqrt(num)
if mod(num, i) == 0
is_prime = false;
break;
end
end
end
disp('Problem 9: Is the number prime?');
disp(is_prime);
% Problem 10: Display Pascal's Triangle using Nested Loops
n = 5; % Number of rows in Pascal's Triangle
disp('Problem 10: Pascal''s Triangle');
for i = 0:n-1
row = 1; % First element in the row
for j = 0:i
fprintf('%d ', row);
row = row * (i - j) / (j + 1); % Calculate next element
end
fprintf('\n'); % Move to the next row
end
% MATLAB Homework: Matrix Solutions
%% 1. Create a 5x5 Matrix
A1 = reshape(1:25, 5, 5)'; % 5x5 matrix with elements 1 to 25 arranged row-wise
disp('1. 5x5 Matrix:');
disp(A1);
%% 2. Element Referencing
b = [10 20 30; 40 50 60; 70 80 90];
element = b(3,2); % Element in 3rd row, 2nd column
disp('2. Element Referencing (3rd row, 2nd column):');
disp(element);
%% 3. Column Vector Creation
v = b(:,1); % First column of matrix b
disp('3. Column Vector (1st column of b):');
disp(v);
%% 4. Sub-matrix Extraction
subMatrix = b(2:3, 1:2); % Last two rows, first two columns
disp('4. 2x2 Sub-Matrix:');
disp(subMatrix);
%% 5. Row Deletion
c = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
c(2,:) = []; % Delete second row
disp('5. Matrix after Row Deletion:');
disp(c);
%% 6. Column Deletion
c(:,3) = []; % Delete third column
disp('6. Matrix after Column Deletion:');
disp(c);
%% 7. Matrix Addition and Subtraction
d = [1 2 3; 4 5 6; 7 8 9];
e = [9 8 7; 6 5 4; 3 2 1];
addResult = d + e; % Matrix addition
subResult = d - e; % Matrix subtraction
disp('7. Matrix Addition (d + e):');
disp(addResult);
disp('Matrix Subtraction (d - e):');
disp(subResult);
%% 8. Matrix Scalar Operations
scalarMultiply = d * 3; % Multiply by 3
scalarDivide = d / 3; % Divide by 3
disp('8. Matrix after Scalar Multiplication (d * 3):');
disp(scalarMultiply);
disp('Matrix after Scalar Division (d / 3):');
disp(scalarDivide);
%% 9. Matrix Transposition
f = [1 3 5; 2 4 6];
fTranspose = f';
disp('9. Transposed Matrix:');
disp(fTranspose);
%% 10. Matrix Inverse and Determinant
g = [1 0 2; 2 1 3; 3 4 1];
det_g = det(g); % Determinant
disp('10. Determinant of Matrix g:');
disp(det_g);
if det_g ~= 0
gInverse = inv(g); % Inverse of g
disp('Inverse of Matrix g:');
disp(gInverse);
else
disp('Matrix g is singular and does not have an inverse.');
end
%% 11. Dynamic Matrix Creation
n = input('Enter the size of the square matrix n: ');
A_dynamic = zeros(n,n);
for i = 1:n
for j = 1:n
A_dynamic(i,j) = i * j;
end
end
disp('11. Dynamic Square Matrix A (i*j):');
disp(A_dynamic);
%% 12. Checkerboard Matrix
n = 8; % Size of checkerboard matrix
checkerboard = mod((1:n)' + (1:n), 2); % Checkerboard logic
disp('12. Checkerboard Matrix (n=8):');
disp(checkerboard);
%% 13. Rotating a Matrix 90 Degrees Clockwise
M = [1 2 3; 4 5 6; 7 8 9]; % Test matrix
rotatedMatrix = M';
rotatedMatrix = flipud(rotatedMatrix);
disp('13. Rotated Matrix (90 Degrees Clockwise):');
disp(rotatedMatrix);
%% 14. Diagonal Dominance Validator
function isDominant = checkDiagonalDominance(X)
n = size(X, 1);
isDominant = true;
for i = 1:n
if abs(X(i,i)) <= sum(abs(X(i,:))) - abs(X(i,i))
isDominant = false;
break;
end
end
end
% Example: Test the diagonal dominance validator
matrixTest = [3 1 1; 1 4 1; 0 2 5];
disp('14. Diagonal Dominance Check:');
if checkDiagonalDominance(matrixTest)
disp('Matrix is diagonally dominant.');
else
disp('Matrix is NOT diagonally dominant.');
end
%% 15. Matrix Pattern Extraction (Cross Shape)
X = magic(7); % Create a 7x7 test matrix
middleRow = X(ceil(end/2), :);
middleColumn = X(:, ceil(end/2));
crossShape = [middleRow; middleColumn'];
disp('15. Extracted Cross Shape from Center of Matrix:');
disp('Middle Row:');
disp(middleRow);
disp('Middle Column:');
disp(middleColumn);
If you have a folder with an enormous number of files and want to use the uigetfile function to select specific files, you may have noticed a significant delay in displaying the file list.
Thanks to the assistance from MathWorks support, an interesting behavior was observed.
For example, if a folder such as Z:\Folder1\Folder2\data contains approximately 2 million files, and you attempt to use uigetfile to access files with a specific extension (e.g., *.ext), the following behavior occurs:
Method 1: This takes minutes to show me the list of all files
[FileName, PathName] = uigetfile('Z:\Folder1\Folder2\data\*.ext', 'File selection');
Method 2: This takes less than a second to display all files.
[FileName, PathName] = uigetfile('*.ext', 'File selection','Z:\Folder1\Folder2\data');
Method 3: This method also takes minutes to display the file list. What is intertesting is that this method is the same as Method 2, except that a file seperator "\" is added at the end of the folder string.
[FileName, PathName] = uigetfile('*.ext', 'File selection','Z:\Folder1\Folder2\data\');
I was informed that the Mathworks development team has been informed of this strange behaviour.
I am using 2023a, but think this should be the same for newer versions.
This post is more of a "tips and tricks" guide than a question.
If you have a folder with an enormous number of files and want to use the uigetfile function to select specific files, you may have noticed a significant delay in displaying the file list.
Thanks to the assistance from MathWorks support, an interesting behavior was observed.
For example, if a folder such as Z:\Folder1\Folder2\data contains approximately 2 million files, and you attempt to use uigetfile to access files with a specific extension (e.g., *.ext), the following behavior occurs:
Method 1: This takes minutes to show me the list of all files
[FileName, PathName] = uigetfile('Z:\Folder1\Folder2\data\*.ext', 'File selection');
Method 2: This takes less than a second to display all files.
[FileName, PathName] = uigetfile('*.ext', 'File selection','Z:\Folder1\Folder2\data');
Method 3: This method also takes minutes to display the file list. What is intertesting is that this method is the same as Method 2, except that a file seperator "\" is added at the end of the folder string.
[FileName, PathName] = uigetfile('*.ext', 'File selection','Z:\Folder1\Folder2\data\');
I was informed that the Mathworks development team has been informed of this strange behaviour.
I am using 2023a, but think this should be the same for newer versions.
I'm beginning this MATLAB-based numerical methods class, and as I was thinking back to my previous MATLAB/Simulink classes, I definitely remember some projects more fondly than others. One of my most memorable was where I had to use MATLAB to analyze electrocardiogram (ECG) peaks. What about you guys? What are some of the best (or worst 🤭) MATLAB projects or assignments you've been given in the past?
Christmas is coming, here are two dynamic Christmas tree drawing codes:
Crystal XMas Tree
function XmasTree2024_1
fig = figure('Units','normalized', 'Position',[.1,.1,.5,.8],...
'Color',[0,9,33]/255, 'UserData',40 + [60,65,75,72,0,59,64,57,74,0,63,59,57,0,1,6,45,75,61,74,28,57,76,57,1,1]);
axes('Parent',fig, 'Position',[0,-1/6,1,1+1/3], 'UserData',97 + [18,11,0,13,3,0,17,4,17],...
'XLim',[-1.5,1.5], 'YLim',[-1.5,1.5], 'ZLim',[-.2,3.8], 'DataAspectRatio', [1,1,1], 'NextPlot','add',...
'Projection','perspective', 'Color',[0,9,33]/255, 'XColor','none', 'YColor','none', 'ZColor','none')
%% Draw Christmas tree
F = [1,3,4;1,4,5;1,5,6;1,6,3;...
2,3,4;2,4,5;2,5,6;2,6,3];
dP = @(V) patch('Faces',F, 'Vertices',V, 'FaceColor',[0 71 177]./255,...
'FaceAlpha',rand(1).*0.2+0.1, 'EdgeColor',[0 71 177]./255.*0.8,...
'EdgeAlpha',0.6, 'LineWidth',0.5, 'EdgeLighting','gouraud', 'SpecularStrength',0.3);
r = .1; h = .8;
V0 = [0,0,0; 0,0,1; 0,r,h; r,0,h; 0,-r,h; -r,0,h];
% Rotation matrix
Rx = @(V, theta) V*[1 0 0; 0 cos(theta) sin(theta); 0 -sin(theta) cos(theta)];
Rz = @(V, theta) V*[cos(theta) sin(theta) 0;-sin(theta) cos(theta) 0; 0 0 1];
N = 180; Vn = zeros(N, 3); eval(char(fig.UserData))
for i = 1:N
tV = Rz(Rx(V0.*(1.2 - .8.*i./N + rand(1).*.1./i^(1/5)), pi/3.*(1 - .6.*i./N)), i.*pi/8.1 + .001.*i.^2) + [0,0,.016.*i];
dP(tV); Vn(i,:) = tV(2,:);
end
scatter3(Vn(:,1).*1.02,Vn(:,2).*1.02,Vn(:,3).*1.01, 30, 'w', 'Marker','*', 'MarkerEdgeAlpha',.5)
%% Draw Star of Bethlehem
w = .3; R = .62; r = .4; T = (1/8:1/8:(2 - 1/8)).'.*pi;
V8 = [ 0, 0, w; 0, 0,-w;
1, 0, 0; 0, 1, 0; -1, 0, 0; 0,-1,0;
R, R, 0; -R, R, 0; -R,-R, 0; R,-R,0;
cos(T).*r, sin(T).*r, T.*0];
F8 = [1,3,25; 1,3,11; 2,3,25; 2,3,11; 1,7,11; 1,7,13; 2,7,11; 2,7,13;
1,4,13; 1,4,15; 2,4,13; 2,4,15; 1,8,15; 1,8,17; 2,8,15; 2,8,17;
1,5,17; 1,5,19; 2,5,17; 2,5,19; 1,9,19; 1,9,21; 2,9,19; 2,9,21;
1,6,21; 1,6,23; 2,6,21; 2,6,23; 1,10,23; 1,10,25; 2,10,23; 2,10,25];
V8 = Rx(V8.*.3, pi/2) + [0,0,3.5];
patch('Faces',F8, 'Vertices',V8, 'FaceColor',[255,223,153]./255,...
'EdgeColor',[255,223,153]./255, 'FaceAlpha', .2)
%% Draw snow
sXYZ = rand(200,3).*[4,4,5] - [2,2,0];
sHdl1 = plot3(sXYZ(1:90,1),sXYZ(1:90,2),sXYZ(1:90,3), '*', 'Color',[.8,.8,.8]);
sHdl2 = plot3(sXYZ(91:200,1),sXYZ(91:200,2),sXYZ(91:200,3), '.', 'Color',[.6,.6,.6]);
annotation(fig,'textbox',[0,.05,1,.09], 'Color',[1 1 1], 'String','Merry Christmas Matlaber',...
'HorizontalAlignment','center', 'FontWeight','bold', 'FontSize',48,...
'FontName','Times New Roman', 'FontAngle','italic', 'FitBoxToText','off','EdgeColor','none');
% Rotate the Christmas tree and let the snow fall
for i=1:1e8
sXYZ(:,3) = sXYZ(:,3) - [.05.*ones(90,1); .06.*ones(110,1)];
sXYZ(sXYZ(:,3)<0, 3) = sXYZ(sXYZ(:,3) < 0, 3) + 5;
sHdl1.ZData = sXYZ(1:90,3); sHdl2.ZData = sXYZ(91:200,3);
view([i,30]); drawnow; pause(.05)
end
end
Curved XMas Tree
function XmasTree2024_2
fig = figure('Units','normalized', 'Position',[.1,.1,.5,.8],...
'Color',[0,9,33]/255, 'UserData',40 + [60,65,75,72,0,59,64,57,74,0,63,59,57,0,1,6,45,75,61,74,28,57,76,57,1,1]);
axes('Parent',fig, 'Position',[0,-1/6,1,1+1/3], 'UserData',97 + [18,11,0,13,3,0,17,4,17],...
'XLim',[-6,6], 'YLim',[-6,6], 'ZLim',[-16, 1], 'DataAspectRatio', [1,1,1], 'NextPlot','add',...
'Projection','perspective', 'Color',[0,9,33]/255, 'XColor','none', 'YColor','none', 'ZColor','none')
%% Draw Christmas tree
[X,T] = meshgrid(.4:.1:1, 0:pi/50:2*pi);
XM = 1 + sin(8.*T).*.05;
X = X.*XM; R = X.^(3).*(.5 + sin(8.*T).*.02);
dF = @(R, T, X) surf(R.*cos(T), R.*sin(T), -X, 'EdgeColor',[20,107,58]./255,...
'FaceColor', [20,107,58]./255, 'FaceAlpha',.2, 'LineWidth',1);
CList = [254,103,110; 255,191,115; 57,120,164]./255;
for i = 1:5
tR = R.*(2 + i); tT = T+i; tX = X.*(2 + i) + i;
SFHdl = dF(tR, tT, tX);
[~, ind] = sort(SFHdl.ZData(:)); ind = ind(1:8);
C = CList(randi([1,size(CList,1)], [8,1]), :);
scatter3(tR(ind).*cos(tT(ind)), tR(ind).*sin(tT(ind)), -tX(ind), 120, 'filled',...
'CData', C, 'MarkerEdgeColor','none', 'MarkerFaceAlpha',.3)
scatter3(tR(ind).*cos(tT(ind)), tR(ind).*sin(tT(ind)), -tX(ind), 60, 'filled', 'CData', C)
end
%% Draw Star of Bethlehem
Rx = @(V, theta) V*[1 0 0; 0 cos(theta) sin(theta); 0 -sin(theta) cos(theta)];
% Rz = @(V, theta) V*[cos(theta) sin(theta) 0;-sin(theta) cos(theta) 0; 0 0 1];
w = .3; R = .62; r = .4; T = (1/8:1/8:(2 - 1/8)).'.*pi;
V8 = [ 0, 0, w; 0, 0,-w;
1, 0, 0; 0, 1, 0; -1, 0, 0; 0,-1,0;
R, R, 0; -R, R, 0; -R,-R, 0; R,-R,0;
cos(T).*r, sin(T).*r, T.*0];
F8 = [1,3,25; 1,3,11; 2,3,25; 2,3,11; 1,7,11; 1,7,13; 2,7,11; 2,7,13;
1,4,13; 1,4,15; 2,4,13; 2,4,15; 1,8,15; 1,8,17; 2,8,15; 2,8,17;
1,5,17; 1,5,19; 2,5,17; 2,5,19; 1,9,19; 1,9,21; 2,9,19; 2,9,21;
1,6,21; 1,6,23; 2,6,21; 2,6,23; 1,10,23; 1,10,25; 2,10,23; 2,10,25];
V8 = Rx(V8.*.8, pi/2) + [0,0,-1.3];
patch('Faces',F8, 'Vertices',V8, 'FaceColor',[255,223,153]./255,...
'EdgeColor',[255,223,153]./255, 'FaceAlpha', .2)
annotation(fig,'textbox',[0,.05,1,.09], 'Color',[1 1 1], 'String','Merry Christmas Matlaber',...
'HorizontalAlignment','center', 'FontWeight','bold', 'FontSize',48,...
'FontName','Times New Roman', 'FontAngle','italic', 'FitBoxToText','off','EdgeColor','none');
%% Draw snow
sXYZ = rand(200,3).*[12,12,17] - [6,6,16];
sHdl1 = plot3(sXYZ(1:90,1),sXYZ(1:90,2),sXYZ(1:90,3), '*', 'Color',[.8,.8,.8]);
sHdl2 = plot3(sXYZ(91:200,1),sXYZ(91:200,2),sXYZ(91:200,3), '.', 'Color',[.6,.6,.6]);
for i=1:1e8
sXYZ(:,3) = sXYZ(:,3) - [.1.*ones(90,1); .12.*ones(110,1)];
sXYZ(sXYZ(:,3)<-16, 3) = sXYZ(sXYZ(:,3) < -16, 3) + 17.5;
sHdl1.ZData = sXYZ(1:90,3); sHdl2.ZData = sXYZ(91:200,3);
view([i,30]); drawnow; pause(.05)
end
end
I wish all MATLABers a Merry Christmas in advance!
I have a problem with the movement of a pawn by two fields in its first move does anyone have a suggestion for a solution
function chess_game()
% Funkcja główna inicjalizująca grę w szachy
% Inicjalizacja stanu gry
gameState = struct();
gameState.board = initialize_board();
gameState.currentPlayer = 'white';
gameState.selectedPiece = [];
% Utworzenie GUI
fig = figure('Name', 'Gra w Szachy', 'NumberTitle', 'off', 'MenuBar', 'none', 'UserData', gameState);
ax = axes('Parent', fig, 'Position', [0 0 1 1], 'XTick', [], 'YTick', []);
axis(ax, [0 8 0 8]);
hold on;
% Wyświetlenie planszy
draw_board(ax, gameState.board);
% Obsługa kliknięcia myszy
set(fig, 'WindowButtonDownFcn', @(src, event)on_click(ax, src));
end
function board = initialize_board()
% Inicjalizuje planszę z ustawieniem początkowym figur
board = {
'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R';
'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p';
'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r';
};
end
function draw_board(~, board)
% Rysuje szachownicę i figury
colors = [1 1 1; 0.8 0.8 0.8];
for row = 1:8
for col = 1:8
% Rysowanie pól
rectColor = colors(mod(row + col, 2) + 1, :);
rectangle('Position', [col-1, 8-row, 1, 1], 'FaceColor', rectColor, 'EdgeColor', 'k');
% Rysowanie figur
piece = board{row, col};
if ~isempty(piece)
text(col-0.5, 8-row+0.5, piece, 'HorizontalAlignment', 'center', ...
'FontSize', 20, 'FontWeight', 'bold');
end
end
end
end
function on_click(ax, fig)
% Funkcja obsługująca kliknięcia myszy
pos = get(ax, 'CurrentPoint');
x = floor(pos(1,1)) + 1; % Zaokrąglij współrzędne w poziomie i dopasuj do indeksów
y = 8 - floor(pos(1,2)); % Dopasuj współrzędne w pionie (odwrócenie osi Y)
% Pobranie stanu gry z figury
gameState = get(fig, 'UserData');
if x >= 1 && x <= 8 && y >= 1 && y <= 8
disp(['Kliknięto na pole: (', num2str(x), ', ', num2str(y), ')']);
if isempty(gameState.selectedPiece)
% Wybór figury
piece = gameState.board{y, x};
if ~isempty(piece)
if (strcmp(gameState.currentPlayer, 'white') && any(ismember(piece, 'RNBQKP'))) || ...
(strcmp(gameState.currentPlayer, 'black') && any(ismember(piece, 'rnbqkp')))
gameState.selectedPiece = [y, x];
disp(['Wybrano figurę: ', piece, ' na pozycji (', num2str(x), ', ', num2str(y), ')']);
else
disp('Nie możesz wybrać tej figury.');
end
else
disp('Nie wybrano figury.');
end
else
% Sprawdzenie, czy kliknięto ponownie na wybraną figurę
if isequal(gameState.selectedPiece, [y, x])
disp('Anulowano wybór figury.');
gameState.selectedPiece = [];
else
% Ruch figury
[sy, sx] = deal(gameState.selectedPiece(1), gameState.selectedPiece(2));
piece = gameState.board{sy, sx};
if is_valid_move(gameState.board, piece, [sy, sx], [y, x], gameState.currentPlayer)
% Wykonanie ruchu
gameState.board{sy, sx} = ''; % Usuwamy figurę z poprzedniego pola
gameState.board{y, x} = piece; % Umieszczamy figurę na nowym polu
gameState.selectedPiece = [];
% Przełącz gracza
gameState.currentPlayer = switch_player(gameState.currentPlayer);
% Odśwież planszę
cla(ax);
draw_board(ax, gameState.board);
else
disp('Ruch niezgodny z zasadami.');
end
end
end
% Zaktualizowanie stanu gry w figurze
set(fig, 'UserData', gameState);
end
end
function valid = is_valid_move(board, piece, from, to, currentPlayer)
% Funkcja sprawdzająca, czy ruch jest poprawny
[sy, sx] = deal(from(1), from(2));
[dy, dx] = deal(to(1), to(2));
dy_diff = dy - sy;
dx_diff = abs(dx - sx);
targetPiece = board{dy, dx};
% Sprawdzenie, czy ruch jest w granicach planszy
if dx < 1 || dx > 8 || dy < 1 || dy > 8
valid = false;
return;
end
% Nie można zbijać swoich figur
if ~isempty(targetPiece) && ...
((strcmp(currentPlayer, 'white') && ismember(targetPiece, 'RNBQKP')) || ...
(strcmp(currentPlayer, 'black') && ismember(targetPiece, 'rnbqkp')))
valid = false;
return;
end
% Zasady ruchu dla każdej figury
switch lower(piece)
case 'p' % Pion
direction = strcmp(currentPlayer, 'white') * 2 - 1; % 1 dla białych, -1 dla czarnych
startRow = strcmp(currentPlayer, 'white') * 2 + 1; % Rząd startowy dla białych i czarnych
if isempty(targetPiece)
% Ruch o jedno pole do przodu
if dy_diff == direction && dx_diff == 0
valid = true;
% Ruch o dwa pola do przodu z pozycji startowej
elseif dy_diff == 2 * direction && dx_diff == 0 && sy == startRow
if isempty(board{sy + direction, sx}) && isempty(board{dy, dx})
valid = true;
else
valid = false;
end
else
valid = false;
end
else
% Zbijanie na ukos
valid = (dx_diff == 1) && (dy_diff == direction);
end
case 'r' % Wieża
valid = (dx_diff == 0 || dy_diff == 0) && path_is_clear(board, from, to);
case 'n' % Skoczek
valid = (dx_diff == 2 && abs(dy_diff) == 1) || (dx_diff == 1 && abs(dy_diff) == 2);
case 'b' % Goniec
valid = (dx_diff == abs(dy_diff)) && path_is_clear(board, from, to);
case 'q' % Hetman
valid = ((dx_diff == 0 || dy_diff == 0) || (dx_diff == abs(dy_diff))) && path_is_clear(board, from, to);
case 'k' % Król
valid = max(abs(dx_diff), abs(dy_diff)) == 1;
otherwise
valid = false;
end
end
function clear = path_is_clear(board, from, to)
% Sprawdza, czy ścieżka między polami jest wolna od innych figur
[sy, sx] = deal(from(1), from(2));
[dy, dx] = deal(to(1), to(2));
stepY = sign(dy - sy);
stepX = sign(dx - sx);
y = sy + stepY;
x = sx + stepX;
while y ~= dy || x ~= dx
if ~isempty(board{y, x})
clear = false;
return;
end
y = y + stepY;
x = x + stepX;
end
clear = true;
end
function nextPlayer = switch_player(currentPlayer)
% Przełącza aktywnego gracza
if strcmp(currentPlayer, 'white')
nextPlayer = 'black';
else
nextPlayer = 'white';
end
end
Speaking as someone with 31+ years of experience developing and using imshow, I want to advocate for retiring and replacing it.
The function imshow has behaviors and defaults that were appropriate for the MATLAB and computer monitors of the 1990s, but which are not the best choice for most image display situations in today's MATLAB. Also, the 31 years have not been kind to the imshow code base. It is a glitchy, hard-to-maintain monster.
My new File Exchange function, imview, illustrates the kind of changes that I think should be made. The function imview is a much better MATLAB graphics citizen and produces higher quality image display by default, and it dispenses with the whole fraught business of trying to resize the containing figure. Although this is an initial release that does not yet support all the useful options that imshow does, it does enough that I am prepared to stop using imshow in my own work.
The Image Processing Toolbox team has just introduced in R2024b a new image viewer called imageshow, but that image viewer is created in a special-purpose window. It does not satisfy the need for an image display function that works well with the axes and figure objects of the traditional MATLAB graphics system.
I have published a blog post today that describes all this in more detail. I'd be interested to hear what other people think.
Note: Yes, I know there is an Image Processing Toolbox function called imview. That one is a stub for an old toolbox capability that was removed something like 15+ years ago. The only thing the toolbox imview function does now is call error. I have just submitted a support request to MathWorks to remove this old stub.
The int function in the Symbolic Toolbox has a hold/release functionality wherein the expression can be held to delay evaluation
syms x I
eqn = I == int(x,x,'Hold',true)
which allows one to show the integral, and then use release to show the result
release(eqn)
Maybe it would be nice to be able to hold/release any symbolic expression to delay the engine from doing evaluations/simplifications that it typically does. For example:
x*(x+1)/x, sin(sym(pi)/3)
If I'm trying to show a sequence of steps to develop a result, maybe I want to explicitly keep the x/x in the first case and then say "now the x in the numerator and denominator cancel and the result is ..." followed by the release command to get the final result.
Perhaps held expressions could even be nested to show a sequence of results upon subsequent releases.
Held expressions might be subject to other limitations, like maybe they can't be fplotted.
Seems like such a capability might not be useful for problem solving, but might be useful for exposition, instruction, etc.
Watt's Up with Electric Vehicles?EV modeling Ecosystem (Eco-friendly Vehicles), V2V Communication and V2I communications thereby emitting zero Emissions to considerably reduce NOx ,Particulates matters,CO2 given that Combustion is always incomplete and will always be.
Reduction of gas emissions outside to the environment will improve human life span ,few epidemic diseases and will result in long life standard
I want to build a neural network that takes a matrix A as input and outputs a matrix B such that a constant C=f(A,B)is maximized as much as possible.(The function f()is a custom complex computation function involving random values,probability density,matrix norms,and a series of other calculations).
I tried to directly use 1/f(A,B)or-f(A,B)as the loss function,but I encountered an error stating:"The value to be differentiated is not tracked.It must be a tracked real number dlarray scalar.Use dlgradient to track variables in the function called by dlfeval."I suspect this is likely because f(A,B)is not differentiable.
However,I've also seen people say that no matter what function it is,the dlgradient function can differentiate it.
So,I'm not sure whether it's because the function f()is too complex to be used as a loss function to calculate gradients,or if there's an issue with my code.
If I can't directly use its reciprocal or negative as the loss function,how should I go about training this neural network?Currently,I only know how to implement:providing target values and using functions like mse or huber as loss functions.
Objectif : Etude d'une chaine de transmission numérique avec des turbo-codes combiné avec la technique HARQ (Hybrid Automatic Repeat reQuest):
* Mettre en place une chaîne de transmission numérique avec des turbo codes intégrant la technique HARQ.
* Évaluer les performances de cette chaîne, en termes de taux d'erreur et de débit sous diverses conditions de canal.
En structurant ainsi votre étude, vous pourrez mener une analyse approfondie des turbo codes et de la technique HARQ.
Outils : Utilisez des outils comme MATLAB, Simulink ou Python (avec des bibliothèques comme Scipy pour la modélisation des canaux et NumPy pour la gestion des calculs).
Simulations : Créez une série de simulations en variant les paramètres comme le SNR, le type de HARQ utilisé, etc.
Compétences développées : Maîtrise des techniques de détection et de correction d’erreurs pour améliorer la fiabilité des transmissions
Hello,
Anyone has basic MATLAB code upon RSMA i.e. to understand basic implementation of RSMA, how to generate common and private messages in MATLAB, etc...?
Always and almost immediately!
25%
Never
30%
After validating existing code
16%
Y'all get the new releases?
29%
1283 个投票
Many of my best friends at MathWorks speak Spanish as their first language and we have a large community of Spanish-speaking users. You can see good evidence of this by checking out our relatively new Spanish YouTube channel which recently crossed the 10,000 subscriber mark
For a project that i am working on, I have to deal with a set of 36 superheated steam tables in one of 3 sheets in an excel file. Since the tables are organized as a set of 5 columns (T,V,U,H,S) with a Pressure "title", but Pressure is a variable I need to be able to read, I want to go about converting the pressure into the first column (unless there is an easier way) of each table where for the length of that table (27 rows) the pressure is the same even as the other variables change (like a matrix). However when I did that I faced a number of issues:
1. the tables didn't separate properly so it combined into 3 tables which is incorrect
2. The pressure column was created but didn't fill with numbers so all showed NaN
3. The column names for the variables are different than my inputs (The columns are listed with units like T_C_ or U_kJ_kg_ and so on, but I need to be able to input any 2 properties and get the rest and I need to be able to input them in the form of T and U and have it understand what columns I am looking for.
3a. When I tried to replace the variable names in the code, Since there are 3 tables it started giving me an error message that there are duplicates of properties when there shouldn't be because they should all be different tables and I want it to recognize that.
Here is a bit of what my table looks like: Please help
Apart optimize angle by Lagrange equation, how many methodes have we about anti-swing for the stabilisation of gantry crane while loading and unloading contenainers? thank you a lot.
hello !! Can we design a control method in backstepping for second order? and how to design it? thank you for all.
I've always used MATLAB with other languages. In the early days, C and C++ via mex files were the most common ways I spliced two languages together. Other than that I've also used MATLAB with Java, Excel and even Fortran.
In more recent years, Python is the language I tend to use most alongside MATLAB and support for this combination is steadily improving. In my latest blog post, I show how easy it has become to use Python's Numpy with MATLAB.
Have you used this functionality much? If so, what for? How well did it work for you?
I am inspired by the latest video from YouTube science content creator Veritasium on his distinct yet thorough explanation on how rainbows work. In his video, he set up a glass sphere experiment representing how light rays would travel inside a raindrop that ultimately forms the rainbow. I highly recommend checking it out.
In the meantime, I created an interactive MATLAB App in MATLAB Online using App Designer to visualize the light paths going through a spherical raindrop with numerical calculations along the way. While I've seen many diagrams out there showing the light paths, I haven't found any doing calculations in each step. Hence I created an app in MATLAB to show the calculations along with the visualizations as one varies the position of the incoming light ray.
Demo video:
For more information about the app and how to open it and play around with it in MATLAB Online, please check out my blog article: