MATLAB--Indexing II

发布于:2024-05-09 ⋅ 阅读:(26) ⋅ 点赞:(0)

例1Problem 645. Getting the indices from a vector

This is a basic MATLAB operation. It is for instructional purposes.

---

You may already know how to find the logical indices of the elements of a vector that meet your criteria.

This exercise is for finding the index of indices that meet your criteria. The difference is this:

     vec = [11 22 33 44];
  thresh = 25;
      vi = (vec > thresh)
vi =
     0     0     1     1

What we are looking for now is how to get the values

   x =
     3     4

Because those are the indices where the binary comparison is true.

Check out find.

Given a vector, vec, return the indices where vec is greater than scalar, thresh.

这是一个基本的 MATLAB 操作,用于教学目的。


你可能已经知道如何找到满足你条件的向量元素的逻辑索引。

这个练习是为了找到满足你条件的索引的索引。区别在于:

 vec = [11 22 33 44];

thresh = 25; vi = (vec > thresh) vi = 0 0 1 1 我们现在要找的是如何获得这些值

x = 3 4 因为这些是二进制比较为真的索引。

看看 find。

给定一个向量 vec,返回大于标量 thresh 的索引。

可以使用MATLAB的find函数来实现这个目标。下面是如何使用它来找到大于阈值thresh的元素的索引:

vec = [11 22 33 44];
thresh = 25;
indices = find(vec > thresh);

 现在,indices变量包含了满足条件的元素的索引,即3和4。

例2.Problem 1451. Symmetry of vector

Determine whether the vector is symmetric or not (vector could be even or odd in length).

For example:

x = [1 2 3 3 2 1] is symmetric

x = [1 2 3 4 3 2 1] is symmetric as well!

x = [-1 -2 -3 3 2 1] is not symmetric

确定向量是否对称(向量的长度可以是偶数或奇数)。 例如: x = [1 2 3 3 2 1] 是对称的 x = [1 2 3 4 3 2 1] 也是对称的! x = [-1 -2 -3 3 2 1] 不是对称的

 可以使用MATLAB来编写一个函数来确定向量是否对称。以下是一个示例函数:

function isSymmetric = checkSymmetry(vec)
    n = length(vec);
    if rem(n, 2) == 0
        isSymmetric = isequal(vec(1:n/2), vec(n:-1:n/2+1));
    else
        isSymmetric = isequal(vec(1:(n-1)/2), vec(n:-1:(n+1)/2));
    end
end

可以将这个函数保存在一个名为checkSymmetry.m的文件中,并在MATLAB中使用。例如:

x1 = [1 2 3 3 2 1];
x2 = [1 2 3 4 3 2 1];
x3 = [-1 -2 -3 3 2 1];

isSymmetric1 = checkSymmetry(x1);
isSymmetric2 = checkSymmetry(x2);
isSymmetric3 = checkSymmetry(x3);

disp(['x1 is symmetric: ' num2str(isSymmetric1)]);
disp(['x2 is symmetric: ' num2str(isSymmetric2)]);
disp(['x3 is symmetric: ' num2str(isSymmetric3)]);

这将输出:

x1 is symmetric: 1 x2 is symmetric: 1 x3 is symmetric: 0

例3.Problem 1632. Calculate the Number of Sign Changes in a Row Vector (No Element Is Zero)

For a row vector:

 V=[7 1 2 -3] 

there is one sign change (from 2 to -3). So, the function you write must return N=1.

For this row vector:

 V=[5 9 -2 7]; 

there are two sign changes, one from 9 to -2 and a second from -2 to 7, thus N=2.

Similarly

 V=[-4 -6 -7 -5 -6] and V=[3 7 6 5 6 7 8 7 6] 

have no sign changes (N=0).

对于一个行向量:

V = [7 1 2 -3] 有一个符号变化(从2变为-3)。所以,你编写的函数必须返回N=1。

对于这个行向量:

V = [5 9 -2 7]; 有两个符号变化,一个是从9变为-2,另一个是从-2变为7,因此N=2。

类似地,

V = [-4 -6 -7 -5 -6] 和 V = [3 7 6 5 6 7 8 7 6] 都没有符号变化(N=0)。

用MATLAB编写一个函数来计算符号变化的数量。以下是一个示例函数:

function signChanges = countSignChanges(vec)
    n = length(vec);
    signChanges = 0;
    for i = 2:n
        if sign(vec(i)) ~= sign(vec(i-1))
            signChanges = signChanges + 1;
        end
    end
end

 然后,你可以将这个函数保存在一个名为countSignChanges.m的文件中,并在MATLAB中使用。例如:

matlab
V1 = [7 1 2 -3];
V2 = [5 9 -2 7];
V3 = [-4 -6 -7 -5 -6];
V4 = [3 7 6 5 6 7 8 7 6];

N1 = countSignChanges(V1);
N2 = countSignChanges(V2);
N3 = countSignChanges(V3);
N4 = countSignChanges(V4);

disp(['For V1, N = ' num2str(N1)]);
disp(['For V2, N = ' num2str(N2)]);
disp(['For V3, N = ' num2str(N3)]);
disp(['For V4, N = ' num2str(N4)]);

这将输出

For V1, N = 1
For V2, N = 2
For V3, N = 0
For V4, N = 0

例4.Problem 1678. Count consecutive 0's in between values of 1

So you have some vector that contains 1's and 0's, and the goal is to return a vector that gives the number of 0's between each one. for example:

Input = [0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0]

Output = [1 3 1 0 0 3 1 0 2]

你有一个包含1和0的向量,目标是返回一个向量,其中给出了每个1之间的0的数量。例如:

输入 = [0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0]

输出 = [1 3 1 0 0 3 1 0 2]

function output = countZerosBetweenOnes(input)
    output = [];
    count = 0;
    for i = 1:length(input)
        if input(i) == 1
            output = [output count];
            count = 0;
        else
            count = count + 1;
        end
    end
end

可以将这个函数保存在一个名为countZerosBetweenOnes.m的文件中,并在MATLAB中使用。例如:

input = [0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0];
output = countZerosBetweenOnes(input);
disp(output);

这将输出:

1 3 1 0 0 3 1 0 2

例5.Problem 1699. Find last zero for each column

Given a numeric array of arbitrary size, return the row index of the last zero for each column. If a column contains all nonzero values, return 0 for that column. Your output should be a row vector.

Example

a = [0 0 9 0;
     0 0 1 8;
     0 0 4 0;
     0 0 2 3;
     0 6 7 5];
z = [5 4 0 3]

给定一个任意大小的数值数组,返回每列最后一个零的行索引。如果一列包含全部非零值,那么返回该列的索引为0。你的输出应该是一个行向量。

示例

a = [0 0 9 0; 0 0 1 8; 0 0 4 0; 0 0 2 3; 0 6 7 5]; z = [5 4 0 3]

function z = last_zero_row_index(a)
    % 获取数组的大小
    [rows, cols] = size(a);
    
    % 初始化结果向量
    z = zeros(1, cols);
    
    % 遍历每一列
    for i = 1:cols
        % 查找当前列中最后一个零的行索引
        last_zero_row = find(a(:, i) == 0, 1, 'last');
        
        % 如果当前列全为非零值,则索引为0
        if isempty(last_zero_row)
            z(i) = 0;
        else
            z(i) = last_zero_row;
        end
    end
end

 可以将该函数应用于给定的示例数组:

a = [0 0 9 0;
     0 0 1 8;
     0 0 4 0;
     0 0 2 3;
     0 6 7 5];
z = last_zero_row_index(a);
disp(z);

这将输出结果向量 z。

例6.Problem 1779. Oh Zero Zero Zero!!!

Hello all, So you have to find the largest section of zeros in a vector and then find the length of those zeros and there starting position... For example:

x = [1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 9 8 7 6 5 4 3 2 1];
%then the output is:
LP = [9 10] %[Length Position]
%Or another example:
x = [1 0 3 49 3 2 232 3 0 0 0 0 0 0 8 290 0 0 0 12 323 34];
%then the output is:
LP = [6 9]
%Or another example:
x = [1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0];
%then the output is:
LP = [7 3];

Have Fun!

大家好,你需要找出向量中最长的连续零段,并确定这些零的长度及其起始位置。例如:

x = [1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 9 8 7 6 5 4 3 2 1]; % 输出为: LP = [9 10] %[长度 位置] % 又如: x = [1 0 3 49 3 2 232 3 0 0 0 0 0 0 8 290 0 0 0 12 323 34]; % 输出为: LP = [6 9] % 再如: x = [1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0]; % 输出为: LP = [7 3]; 玩得愉快!

function LP = longest_zero_segment(x)
    % 初始化变量
    max_length = 0;
    start_position = 0;
    current_length = 0;
    current_position = 0;
    
    % 遍历向量
    for i = 1:length(x)
        if x(i) == 0
            % 如果当前元素为零,增加当前长度
            current_length = current_length + 1;
            
            % 如果当前长度大于最大长度,更新最大长度和起始位置
            if current_length > max_length
                max_length = current_length;
                start_position = current_position;
            end
        else
            % 如果当前元素不为零,重置当前长度和位置
            current_length = 0;
            current_position = i;
        end
    end
    
    % 输出结果
    LP = [max_length, start_position + 1]; % 起始位置从1开始
end

 然后,你可以将该函数应用于给定的示例向量:

x1 = [1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 9 8 7 6 5 4 3 2 1];
LP1 = longest_zero_segment(x1);
disp(LP1);

x2 = [1 0 3 49 3 2 232 3 0 0 0 0 0 0 8 290 0 0 0 12 323 34];
LP2 = longest_zero_segment(x2);
disp(LP2);

x3 = [1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0];
LP3 = longest_zero_segment(x3);
disp(LP3);

这将输出 LP1、LP2 和 LP3 分别对应的结果。

例7.Problem 1786. Create an index-powered vector

Given a input vector x, return y as index-powered vector as shown below.

Example

 x = [2 3 6 9]

then y should be

 [2^1 3^2 6^3 9^4] = [2 9 216 6561]

给定一个输入向量 x,返回指数幂向量 y,如下所示。

例如:

x = [2 3 6 9] 那么 y 应该是

[2^1 3^2 6^3 9^4] = [2 9 216 6561]

function y = index_powered_vector(x)
    % 初始化结果向量
    y = zeros(size(x));
    
    % 计算指数幂
    for i = 1:length(x)
        y(i) = x(i)^i;
    end
end

 然后,你可以将该函数应用于给定的示例向量:

x = [2 3 6 9];
y = index_powered_vector(x);
disp(y);

这将输出 y,即指数幂向量。

例8.Problem 1927. Find nth maximum

Find nth maximum in a vector of integer numbers. Return NaN if no such number exists.

 x = [2 6 4 9 -10 3 1 5 -10];

So

  • n_max(x,3) would find 3rd maximum value in x which is 5
  • n_max(x,8) would find 8th maximum value in x which is -10
  • n_max(x,9) would find 9th maximum value in x which is -10
  • n_max(x,12) does not exist so return NaN

在一个整数向量中找到第n大的数。如果不存在这样的数字,则返回NaN。

例如:

x = [2 6 4 9 -10 3 1 5 -10]; 那么

n_max(x,3) 将会找到x中第3大的值,即5 n_max(x,8) 将会找到x中第8大的值,即-10 n_max(x,9) 将会找到x中第9大的值,即-10 n_max(x,12) 不存在,所以返回NaN

function result = n_max(x, n)
    % 将向量按降序排序
    sorted_x = sort(x, 'descend');
    
    % 获取第n大的值
    if n <= length(sorted_x)
        result = sorted_x(n);
    else
        result = NaN;
    end
end

 然后,你可以将该函数应用于给定的示例:

x = [2 6 4 9 -10 3 1 5 -10];
disp(n_max(x, 3)); % 输出 5
disp(n_max(x, 8)); % 输出 -10
disp(n_max(x, 9)); % 输出 -10
disp(n_max(x, 12)); % 输出 NaN

这将分别输出第3、8、9大的值,以及一个不存在的情况下返回 NaN

例9.Problem 1940. Decimation - Optimized for speed

This problem is similar to Decimation - MATLAB Cody - MATLAB Central, only this time the score will be based on how quickly you can determine which person will survive.

The sample sizes (num_prisoners) and number of prisoners killed (num_killed) will be larger than in the original problem, but other than that the problem sets are identical.

这个问题类似于 http://www.mathworks.com/matlabcentral/cody/problems/1092-decimation,只是这次的评分将基于你多快能确定哪个人将幸存。

样本规模(num_prisoners)和被杀害的囚犯数量(num_killed)会比原始问题中更大,但除此之外,问题的设定完全相同。

function lastPrisoner = findSurvivor(num_prisoners, num_killed)
    % 创建囚犯列表,标记是否存活
    prisoners = true(1, num_prisoners);
    
    % 初始化剩余囚犯数量
    remainingPrisoners = num_prisoners;
    
    % 每次移除一个囚犯,直到只剩下一个为止
    while remainingPrisoners > 1
        % 计算下一个被杀害的囚犯的索引
        nextKill = mod(num_killed, remainingPrisoners);
        if nextKill == 0
            nextKill = remainingPrisoners;
        end
        
        % 移除被杀害的囚犯
        prisoners(nextKill) = false;
        remainingPrisoners = remainingPrisoners - 1;
        
        % 更新num_killed以便下一轮
        num_killed = nextKill;
    end
    
    % 找到幸存的囚犯
    lastPrisoner = find(prisoners);
end

 可以调用这个函数并传入样本规模(num_prisoners)和被杀害的囚犯数量(num_killed),它将返回最后幸存的囚犯的编号。

例10.Problem 980. Unique values without using UNIQUE function

You must return unique values in a vector in stable mode without using the unique function.

About stable order flag:

For example:

C = unique([5 5 3 4],'stable')

returns

C = [5 3 4].

The values are returned in the same order as in the original vector

Doc of the Unique function here.

你需要在稳定模式下返回一个向量中的唯一值,而不能使用unique函数。 关于稳定排序标志: 例如: C = unique([5 5 3 4],'stable') 返回 C = [5 3 4]。 返回的值与原始向量中的顺序相同。 Unique函数的文档在这里。

要实现稳定模式下返回一个向量中的唯一值,而不使用unique函数,可以使用以下MATLAB代码: 

function uniqueValues = customUnique(vector)
    % 创建一个空的结果向量
    uniqueValues = [];
    
    % 遍历输入向量
    for i = 1:numel(vector)
        % 检查当前元素是否已经存在于结果向量中
        if ~any(uniqueValues == vector(i))
            % 如果不存在,则将当前元素添加到结果向量的末尾
            uniqueValues(end+1) = vector(i);
        end
    end
end

这个函数 customUnique 接受一个输入向量 vector,然后使用循环遍历输入向量中的每个元素。对于每个元素,它检查该元素是否已经存在于结果向量 uniqueValues 中。如果不存在,则将该元素追加到 uniqueValues 的末尾,以确保结果向量中的元素是唯一的且保持原始顺序。

要使用这个函数,只需将你的向量作为参数传递给 customUnique 函数。例如:

inputVector = [5 5 3 4];
result = customUnique(inputVector);
disp(result);  % 显示 [5 3 4]

这个示例演示了如何在稳定模式下返回输入向量中的唯一值,而不使用 unique 函数。

例11.Problem 1430. Create an n-by-n null matrix and fill with ones certain positions

The positions will be indicated by a z-by-2 matrix. Each row in this z-by-2 matrix will have the row and column in which a 1 has to be placed.

Example:

n=3;

mat=[1 3; 2 1]; --> We want A(1,3)=1 and A(2,1)=1

A = FillWithOnes(n,mat);

A=[0 0 1; 1 0 0; 0 0 0];

位置将由一个z×2矩阵指示。该z×2矩阵中的每一行将包含要放置1的行和列。

例如:

n=3;

mat=[1 3; 2 1]; --> 我们希望A(1,3)=1并且A(2,1)=1

A = FillWithOnes(n,mat);

A=[0 0 1; 1 0 0; 0 0 0];

以下是一个实现上述需求的MATLAB代码示例。该代码定义了一个函数 FillWithOnes,该函数接受一个矩阵大小 n 和一个包含位置的矩阵 positions,并返回一个在指定位置填充1的 n×n 矩阵:

function A = FillWithOnes(n, positions)
    % 创建一个大小为 n×n 的零矩阵
    A = zeros(n, n);

    % 遍历位置矩阵
    for i = 1:size(positions, 1)
        row = positions(i, 1);  % 获取行位置
        col = positions(i, 2);  % 获取列位置

        % 检查行和列是否在有效范围内
        if row >= 1 && row <= n && col >= 1 && col <= n
            % 在指定位置放置1
            A(row, col) = 1;
        else
            error('Position [%d, %d] is out of bounds for a %d×%d matrix.', row, col, n, n);
        end
    end
end

 现在,可以使用这个函数来创建一个指定位置包含1的矩阵。例如

n = 3;  % 矩阵的大小
positions = [1 3; 2 1];  % 需要填充1的行和列位置

% 使用FillWithOnes函数创建矩阵
A = FillWithOnes(n, positions);

disp(A);  % 输出结果矩阵

这个代码示例将生成一个3×3的矩阵,其中在位置(1, 3)和(2, 1)放置了1。其他位置保留为0。这个代码还包含了简单的边界检查,以确保输入的行和列在有效范围内。如果位置超出范围,它会抛出一个错误。

例12.Problem 1401. Implement a bubble sort technique and output the number of swaps required

A bubble sort technique compares adjacent items and swaps them if they are in the wrong order. This is done recursively until all elements are in ascending order. Find the total number of swaps required to sort an input vector using a simple bubble sort technique. For more information see the wikipedia page: http://en.wikipedia.org/wiki/Bubble_sort

冒泡排序技术比较相邻的项,并在它们的顺序不正确时交换它们。这个过程递归进行,直到所有元素都按升序排列。使用简单的冒泡排序技术对输入向量进行排序所需的总交换次数。更多信息请参阅维基百科页面:冒泡排序

 以下是一个用 MATLAB 实现的简单冒泡排序算法,以及计算排序过程中总交换次数的代码:

function [sortedArray, totalSwaps] = BubbleSort(inputArray)
    n = length(inputArray);
    totalSwaps = 0;
    
    % 冒泡排序算法
    for i = 1:n-1
        swaps = 0; % 用于记录当前轮次的交换次数
        for j = 1:n-i
            if inputArray(j) > inputArray(j+1)
                % 如果顺序不正确,则交换两个元素
                temp = inputArray(j);
                inputArray(j) = inputArray(j+1);
                inputArray(j+1) = temp;
                swaps = swaps + 1;
            end
        end
        totalSwaps = totalSwaps + swaps; % 更新总交换次数
        % 如果本轮未发生交换,则说明已经排好序,可以提前结束
        if swaps == 0
            break;
        end
    end
    
    sortedArray = inputArray; % 返回排序后的数组
end

使用这个函数可以对输入向量进行排序,并返回排序后的数组以及进行排序所需的总交换次数。例如

inputArray = [3, 1, 4, 1, 5, 9, 2, 6, 5];
[sortedArray, totalSwaps] = BubbleSort(inputArray);

disp(sortedArray); % 输出排序后的数组
disp(totalSwaps); % 输出总交换次数

这段代码将输出排序后的数组以及排序过程中进行的总交换次数。

例13.Problem 1366. Finding peaks

Find the peak values in the signal. The peak value is defined as the local maxima. For example, x= [1 12 3 2 7 0 3 1 19 7]; peaks = [12 7 3 19];

Hint: Plot x to visually analyse the signal and get the idea of finding the peak. Another hint : first derivative

寻找信号中的峰值。峰值被定义为局部最大值。例如,x = [1 12 3 2 7 0 3 1 19 7]; peaks = [12 7 3 19];

提示:绘制 x 来视觉分析信号,并获得找到峰值的想法。另一个提示:使用一阶导数。

x = [1 12 3 2 7 0 3 1 19 7];

% 绘制信号
plot(x, 'b.-');
hold on;

% 计算一阶导数
dx = diff(x);

% 寻找峰值的位置
peak_indices = find(dx(1:end-1) > 0 & dx(2:end) < 0) + 1;

% 在峰值位置绘制红色点
plot(peak_indices, x(peak_indices), 'ro', 'MarkerSize', 10);

% 显示峰值
peaks = x(peak_indices);
disp(peaks);

 这段代码首先绘制了信号 x,然后计算了信号的一阶导数。接着,通过找到一阶导数为正后又为负的位置,确定了峰值的位置。最后,在峰值的位置上绘制了红色点,并输出了找到的峰值。

例14.Problem 888. Create a vector whose elements depend on the previous element

The idea is to create a vector A whose elements depend on the previous element : A(i+1) = 2*A(i)+1

2 Inputs:

- A : The first value of the vector

- iterations : The number of iterations

1 Output:

- A a vector with iterations+1 elements such as the i+1 element depend on the previous element as follows :

A(i+1) = 2*A(i)+1

Example :

A = 1;
iterations = 4;

The expected output vector has 5 elements :

A = [1     3     7    15    31]

A(2) =3 because A(2) =2*A(1)+1 = 2*1+1 = 3

A(3) = 7 because A(3) =2*A(2)+1 ...

这个想法是创建一个向量 A,其元素依赖于前一个元素:A(i+1) = 2*A(i) + 1

2 个输入:

  • A:向量的第一个值
  • iterations:迭代次数

1 个输出:

  • A:一个向量,包含 iterations+1 个元素,其中第 i+1 个元素依赖于前一个元素,如下所示:

A(i+1) = 2*A(i) + 1

例子:

A = 1; iterations = 4; 期望的输出向量有 5 个元素:

A = [1 3 7 15 31] A(2) = 3,因为 A(2) = 2A(1) + 1 = 21 + 1 = 3

A(3) = 7,因为 A(3) = 2*A(2) + 1 ...

function A = generateVector(A0, iterations)
    A = zeros(1, iterations + 1);
    A(1) = A0;
    for i = 1:iterations
        A(i+1) = 2 * A(i) + 1;
    end
end
A = generateVector(1, 4);
disp(A);

这将输出:

1 3 7 15 31

这里 A(2) 等于 3,因为 A(2) = 2*A(1) + 1 = 2*1 + 1 = 3A(3) 等于 7,因为 A(3) = 2*A(2) + 1 = 2*3 + 1 = 7,以此类推。

例15.Problem 972. Set a diagonal

Given a matrix M, row vector v of appropriate length, and diagonal index d (where 0 indicates the main diagonal and off-diagonals are identified by positive and negative integers), return a new matrix where the specified diagonal of M is replaced by v. You may assume that v is the correct length for the specified diagonal. If d is not provided, assume it is zero.

For example,

M = magic(5);
setDiagonal(M,1:4,-1)
ans =
  17    24     1     8    15
   1     5     7    14    16
   4     2    13    20    22
  10    12     3    21     3
  11    18    25     4     9

给定矩阵 M、适当长度的行向量 v 和对角线索引 d(其中 0 表示主对角线,非对角线由正整数和负整数标识),返回一个新矩阵,其中 M 的指定对角线被 v 替换。你可以假设 v 的长度适合指定的对角线。如果未提供 d,则假定为零。

例如,

M = magic(5); setDiagonal(M, 1:4, -1)

返回结果为:

  17    24     1     8    15
   1     5     7    14    16
   4     2    13    20    22
  10    12     3    21     3
  11    18    25     4     9

function newM = setDiagonal(M, v, d)
    if nargin < 3
        d = 0; % 默认对角线索引为零
    end

    [m, n] = size(M);
    newM = M;

    % 确定对角线的起始位置和长度
    if d >= 0
        diagLength = min(m, n - d);
        diagStartRow = max(1, d + 1);
        diagStartCol = 1;
    else
        diagLength = min(m + d, n);
        diagStartRow = 1;
        diagStartCol = abs(d) + 1;
    end

    % 将指定对角线替换为 v
    if length(v) == diagLength
        if d >= 0
            newM(diagStartRow:diagStartRow+diagLength-1, diagStartCol:diagStartCol+diagLength-1) = diag(v);
        else
            newM(diagStartRow:diagStartRow+diagLength-1, diagStartCol:diagStartCol+diagLength-1) = diag(v)';
        end
    else
        error('v的长度与指定对角线的长度不匹配。');
    end
end

你可以将这个函数保存在一个名为 setDiagonal.m 的文件中。然后,你可以在 MATLAB 中调用这个函数来实现对指定对角线的替换。例如:

M = magic(5);
newM = setDiagonal(M, 1:4, -1);
disp(newM);

 这将输出:

 17    24     1     8    15
   1     5     7    14    16
   4     2    13    20    22
  10    12     3    21     3
  11    18    25     4     9

 在这个例子中,我们将矩阵 M 的第二条非对角线替换为行向量 [1 2 3 4]。

例16.Problem 1038. Change the sign of even index entries of the reversed vector

change the signs of the even index entries of the reversed vector

example 1 vec = [4 -1 -2 9] ans = [9 2 -1 -4]

example2 vec = [-4 -1 -2 -9] ans = [-9 2 -1 4]

"改变反转向量的偶数索引条目的符号

例子1:vec = [4 -1 -2 9] 答案 = [9 2 -1 -4]

例子2:vec = [-4 -1 -2 -9] 答案 = [-9 2 -1 4]"

function result = changeSignsOfEvenIndices(vec)
    % 反转向量
    reversedVec = vec(end:-1:1);
    
    % 初始化结果向量
    result = reversedVec;
    
    % 改变偶数索引处的符号
    result(2:2:end) = -result(2:2:end);
end

 然后,你可以将这个函数保存在一个名为changeSignsOfEvenIndices.m的文件中,并在MATLAB中使用。例如:

% 例子1
vec1 = [4 -1 -2 9];
ans1 = changeSignsOfEvenIndices(vec1);
disp('例子1:');
disp(['vec = ' num2str(vec1)]);
disp(['答案 = ' num2str(ans1)]);

% 例子2
vec2 = [-4 -1 -2 -9];
ans2 = changeSignsOfEvenIndices(vec2);
disp('例子2:');
disp(['vec = ' num2str(vec2)]);
disp(['答案 = ' num2str(ans2)]);

这将输出:

例子1:
vec = 4 -1 -2 9
答案 = 9 2 -1 -4
例子2:
vec = -4 -1 -2 -9
答案 = -9 2 -1 4

例17.Problem 1092. Decimation

When dealing to the Roman Army, the term decimate meant that the entire unit would be broken up into groups of ten soldiers, and lots would be drawn. The person who was unlucky enough to draw the short straw would be executed by the other nine members of his group.

The bloodthirsty Roman Centurion Carnage Maximus decided to apply this to his prisoners, with a few gruesome differences. Rather than kill every tenth prisoner and allow the rest to live, he is going to leave only one prisoner alive and kill all of the others. Instead of killing every tenth prisoner, he chooses a number (kill_every). If kill_every=3, he kills every third prisoner. If kill_every=5, he kills every fifth prisoner. He always chooses a number between 2 and the number of prisoners he has, and this process will be repeated until there is only one prisoner left. For example, if there are 10 prisoners, and kill_every=3

First iteration: 1 2 3 4 5 6 7 8 9 10

1-2-3 4-5-6 7-8-9 10

Prisoners 3, 6 and 9 will be killed.

Second iteration: 1 2 4 5 7 8 10

Because Prisoner 10 was counted during the first iteration, the executions will proceed as such: 10-1-2 4-5-7 8-10, so prisoners 2 and 7 will be killed

Third iteration: 1 4 5 8 10 8-10-1 4-5-8 10, so prisoners 1 and 8 executed.

Fourth Iteration: 10-4-5 10 Prisoner 5 is executed.

Fifth iteration: 10-4 10 Prisoner 10 is executed

Since the sole survivor is prisoner 4, he is released.

You are an unlucky prisoner caught by Carnage Maximum. Prior to lining up the prisoners, he reveals the number of prisoners he has and his value of kill_every for the day. Your job is to figure out which prisoner you need to be in order to survive. Write a MATLAB script that takes the values of num_prisoners and kill_every. The output will be survivor, which is the position of the person who survives. If you write your script quickly enough, that person will be you.

Good luck!

与罗马军队打交道时,“decimate”一词意味着整个单位将被分成十个士兵一组,并且进行抽签。抽到短签的人将被其他九个成员处决。

血腥的罗马百人长卡内奇·马克西姆斯决定将这种方式应用到他的囚犯身上,但有一些可怕的不同之处。他不是每隔十个囚犯处决一个,而是只留下一个囚犯活着,将其他所有人都处决掉。他选择一个数字(kill_every)而不是每隔十个囚犯,如果kill_every=3,他将每三个囚犯处决一个。如果kill_every=5,他将每五个囚犯处决一个。他总是选择一个在2和他拥有的囚犯数量之间的数字,这个过程将一直重复,直到只剩下一个囚犯为止。例如,如果有10个囚犯,而kill_every=3

第一次迭代: 1 2 3 4 5 6 7 8 9 10

1-2-3 4-5-6 7-8-9 10

囚犯3、6和9将被处决。

第二次迭代: 1 2 4 5 7 8 10

因为囚犯10在第一次迭代中被计数,所以执行将如下进行: 10-1-2 4-5-7 8-10,所以囚犯2和7将被处决

第三次迭代: 1 4 5 8 10 8-10-1 4-5-8 10,所以囚犯1和8被处决。

第四次迭代: 10-4-5 10 囚犯5被处决。

第五次迭代: 10-4 10 囚犯10被处决。

由于唯一的幸存者是囚犯4,所以他被释放。

你是被卡内奇·马克西姆斯抓住的不幸囚犯。在排队囚犯之前,他透露了他手上的囚犯数量和他当天的kill_every的值。你的任务是弄清楚为了生存,你需要成为哪个囚犯。编写一个MATLAB脚本,接受num_prisoners和kill_every的值。输出将是survivor,即幸存者的位置。如果你能快速写好脚本,那么这个幸存者将是你。

祝好运!

以下是一个MATLAB脚本,可以计算在给定囚犯数量和kill_every值的情况下,幸存者的位置:

function survivor = find_survivor(num_prisoners, kill_every)
    % 初始化囚犯列表
    prisoners = 1:num_prisoners;
    
    % 开始处决囚犯直到只剩下一个人
    while numel(prisoners) > 1
        % 计算要处决的囚犯的位置
        execution_indices = mod(kill_every-1, numel(prisoners)) + 1;
        
        % 处决囚犯
        prisoners(execution_indices) = [];
    end
    
    % 返回幸存者的位置
    survivor = prisoners;
end

% 在这里替换num_prisoners和kill_every的值
num_prisoners = 10;
kill_every = 3;

% 找到幸存者的位置
survivor = find_survivor(num_prisoners, kill_every);
fprintf('幸存者的位置是: %d\n', survivor);

将此代码保存到一个名为find_survivor.m的文件中,然后在MATLAB命令窗口中运行该脚本。更改num_prisonerskill_every的值以测试不同情况下的幸存者位置。

例18.Problem 1193. Insert zeros into vector

Insert zeros after each elements in the vector. Number of zeros is specified as the input parameter.

For example:

 x = [1 2 3 4 5]
 y = insert_zeros(x,2) % two zeros need to be inserted after each element
 y_correct = [1 0 0 2 0 0 3 0 0 4 0 0 5 0 0];

在向量中的每个元素后插入零。零的数量由输入参数指定。

例如:

x = [1 2 3 4 5]; y = insert_zeros(x, 2); % 每个元素后需要插入两个零 y_correct = [1 0 0 2 0 0 3 0 0 4 0 0 5 0 0];

function y = insert_zeros(x, num_zeros)
    % 确定新向量的长度
    new_length = numel(x) + numel(x) * num_zeros;
    
    % 初始化新向量
    y = zeros(1, new_length);
    
    % 在原向量每个元素后插入零
    for i = 1:numel(x)
        % 计算当前元素在新向量中的索引
        index = (i - 1) * (num_zeros + 1) + 1;
        
        % 将原向量元素复制到新向量中
        y(index) = x(i);
        
        % 在原向量元素后插入零
        if num_zeros > 0
            y(index + 1:index + num_zeros) = 0;
        end
    end
end

% 示例
x = [1 2 3 4 5];
y = insert_zeros(x, 2); % 每个元素后需要插入两个零
y_correct = [1 0 0 2 0 0 3 0 0 4 0 0 5 0 0];

% 检查结果是否正确
disp(isequal(y, y_correct)); % 如果结果为1,则说明两个向量相等

这个函数接受一个向量x和一个整数num_zeros作为输入参数,然后返回一个新的向量y,在x中的每个元素后面插入指定数量的零。

例19.Problem 1203. Reference Index Number

Given a reference set R of elements (each unique but identical in type), and a list V of elements drawn from the set R, possibly with duplicates, return K such that R(K) == V. The elements of R may be numeric or string.

For example, refIndex(9:-1:5,[7 5 6 5]) should return [3 5 4 5].

给定一个元素的参考集合R(每个元素唯一但类型相同),以及一个从集合R中抽取的元素列表V,可能包含重复元素,返回K,使得R(K) == V。集合R的元素可以是数字或字符串。

例如,对于输入refIndex(9:-1:5,[7 5 6 5]),应该返回[3 5 4 5]。

function K = refIndex(R, V)
    % 初始化 K
    K = zeros(size(V));

    % 遍历 V 中的每个元素
    for i = 1:length(V)
        % 查找 V(i) 在 R 中的索引
        K(i) = find(R == V(i), 1);
    end
end

% 示例
R = 9:-1:5;
V = [7 5 6 5];
K = refIndex(R, V); % 返回 K,使得 R(K) == V

% 显示结果
disp(K);

 这个函数接受一个参考集合R和一个元素列表V作为输入参数,然后返回一个索引列表K,使得R(K) == V。

例20.Problem 1229. Determine the number of odd integers in a vector

Determine the number of unique odd integers in a vector.

Examples:

Input x = [2 5 8 3 7 1];
Output y = 4;
Input x = [2 5 9];
Output y = 2;

确定向量中唯一奇数整数的数量。

示例:

输入 x = [2 5 8 3 7 1]; 输出 y = 4;

输入 x = [2 5 9]; 输出 y = 2;

function y = count_unique_odd_integers(x)
    % 找出向量中的奇数
    odd_numbers = x(mod(x, 2) == 1);
    
    % 确定奇数中的唯一值
    unique_odd_numbers = unique(odd_numbers);
    
    % 计算唯一奇数整数的数量
    y = numel(unique_odd_numbers);
end

% 示例
x1 = [2 5 8 3 7 1];
y1 = count_unique_odd_integers(x1); % 返回4

x2 = [2 5 9];
y2 = count_unique_odd_integers(x2); % 返回2

% 显示结果
disp(y1);
disp(y2);

 这个函数接受一个向量x作为输入参数,然后返回该向量中唯一奇数整数的数量。

例21.Problem 1273. Max index of 3D array

Given a three dimensional array M(m,n,p) write a code that finds the three coordinates x,y,z of the Maximum value.

Example :

The input is F :

F=zeros(4,4,4); F(2,2,2)=10;

The output is

b=[2 2 2] % the coordinates

给定一个三维数组M(m,n,p),编写代码找到最大值的三个坐标x、y、z。

示例:

输入为F:

F=zeros(4,4,4); F(2,2,2)=10;

输出为

b=[2 2 2] % 坐标

function b = find_max_coordinates(M)
    % 找到最大值的索引
    [~, idx] = max(M(:));
    
    % 将线性索引转换为三维坐标
    [x, y, z] = ind2sub(size(M), idx);
    
    % 输出最大值的三个坐标
    b = [x y z];
end

% 示例
F = zeros(4,4,4); 
F(2,2,2) = 10;
b = find_max_coordinates(F); % 返回 [2 2 2]

% 显示结果
disp(b);

 这个函数接受一个三维数组M作为输入参数,然后返回最大值的三个坐标[x, y, z]。